babylon.max.js 5.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554
  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. var SmartArray = /** @class */ (function () {
  8485. function SmartArray(capacity) {
  8486. this.length = 0;
  8487. this.data = new Array(capacity);
  8488. this._id = SmartArray._GlobalId++;
  8489. }
  8490. SmartArray.prototype.push = function (value) {
  8491. this.data[this.length++] = value;
  8492. if (this.length > this.data.length) {
  8493. this.data.length *= 2;
  8494. }
  8495. };
  8496. SmartArray.prototype.forEach = function (func) {
  8497. for (var index = 0; index < this.length; index++) {
  8498. func(this.data[index]);
  8499. }
  8500. };
  8501. SmartArray.prototype.sort = function (compareFn) {
  8502. this.data.sort(compareFn);
  8503. };
  8504. SmartArray.prototype.reset = function () {
  8505. this.length = 0;
  8506. };
  8507. SmartArray.prototype.dispose = function () {
  8508. this.reset();
  8509. if (this.data) {
  8510. this.data.length = 0;
  8511. this.data = [];
  8512. }
  8513. };
  8514. SmartArray.prototype.concat = function (array) {
  8515. if (array.length === 0) {
  8516. return;
  8517. }
  8518. if (this.length + array.length > this.data.length) {
  8519. this.data.length = (this.length + array.length) * 2;
  8520. }
  8521. for (var index = 0; index < array.length; index++) {
  8522. this.data[this.length++] = (array.data || array)[index];
  8523. }
  8524. };
  8525. SmartArray.prototype.indexOf = function (value) {
  8526. var position = this.data.indexOf(value);
  8527. if (position >= this.length) {
  8528. return -1;
  8529. }
  8530. return position;
  8531. };
  8532. SmartArray.prototype.contains = function (value) {
  8533. return this.data.indexOf(value) !== -1;
  8534. };
  8535. // Statics
  8536. SmartArray._GlobalId = 0;
  8537. return SmartArray;
  8538. }());
  8539. BABYLON.SmartArray = SmartArray;
  8540. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8541. __extends(SmartArrayNoDuplicate, _super);
  8542. function SmartArrayNoDuplicate() {
  8543. var _this = _super !== null && _super.apply(this, arguments) || this;
  8544. _this._duplicateId = 0;
  8545. return _this;
  8546. }
  8547. SmartArrayNoDuplicate.prototype.push = function (value) {
  8548. _super.prototype.push.call(this, value);
  8549. if (!value.__smartArrayFlags) {
  8550. value.__smartArrayFlags = {};
  8551. }
  8552. value.__smartArrayFlags[this._id] = this._duplicateId;
  8553. };
  8554. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8555. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8556. return false;
  8557. }
  8558. this.push(value);
  8559. return true;
  8560. };
  8561. SmartArrayNoDuplicate.prototype.reset = function () {
  8562. _super.prototype.reset.call(this);
  8563. this._duplicateId++;
  8564. };
  8565. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8566. if (array.length === 0) {
  8567. return;
  8568. }
  8569. if (this.length + array.length > this.data.length) {
  8570. this.data.length = (this.length + array.length) * 2;
  8571. }
  8572. for (var index = 0; index < array.length; index++) {
  8573. var item = (array.data || array)[index];
  8574. this.pushNoDuplicate(item);
  8575. }
  8576. };
  8577. return SmartArrayNoDuplicate;
  8578. }(SmartArray));
  8579. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8580. })(BABYLON || (BABYLON = {}));
  8581. //# sourceMappingURL=babylon.smartArray.js.map
  8582. var BABYLON;
  8583. (function (BABYLON) {
  8584. /** Class used to store color gradient */
  8585. var ColorGradient = /** @class */ (function () {
  8586. function ColorGradient() {
  8587. }
  8588. /**
  8589. * Will get a color picked randomly between color1 and color2.
  8590. * If color2 is undefined then color1 will be used
  8591. * @param result defines the target Color4 to store the result in
  8592. */
  8593. ColorGradient.prototype.getColorToRef = function (result) {
  8594. if (!this.color2) {
  8595. result.copyFrom(this.color1);
  8596. return;
  8597. }
  8598. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8599. };
  8600. return ColorGradient;
  8601. }());
  8602. BABYLON.ColorGradient = ColorGradient;
  8603. /** Class used to store factor gradient */
  8604. var FactorGradient = /** @class */ (function () {
  8605. function FactorGradient() {
  8606. }
  8607. /**
  8608. * Will get a number picked randomly between factor1 and factor2.
  8609. * If factor2 is undefined then factor1 will be used
  8610. * @returns the picked number
  8611. */
  8612. FactorGradient.prototype.getFactor = function () {
  8613. if (this.factor2 === undefined) {
  8614. return this.factor1;
  8615. }
  8616. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8617. };
  8618. return FactorGradient;
  8619. }());
  8620. BABYLON.FactorGradient = FactorGradient;
  8621. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8622. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8623. var LoadFileError = /** @class */ (function (_super) {
  8624. __extends(LoadFileError, _super);
  8625. function LoadFileError(message, request) {
  8626. var _this = _super.call(this, message) || this;
  8627. _this.request = request;
  8628. _this.name = "LoadFileError";
  8629. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8630. return _this;
  8631. }
  8632. // Polyfill for Object.setPrototypeOf if necessary.
  8633. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8634. return LoadFileError;
  8635. }(Error));
  8636. BABYLON.LoadFileError = LoadFileError;
  8637. var RetryStrategy = /** @class */ (function () {
  8638. function RetryStrategy() {
  8639. }
  8640. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8641. if (maxRetries === void 0) { maxRetries = 3; }
  8642. if (baseInterval === void 0) { baseInterval = 500; }
  8643. return function (url, request, retryIndex) {
  8644. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8645. return -1;
  8646. }
  8647. return Math.pow(2, retryIndex) * baseInterval;
  8648. };
  8649. };
  8650. return RetryStrategy;
  8651. }());
  8652. BABYLON.RetryStrategy = RetryStrategy;
  8653. // Screenshots
  8654. var screenshotCanvas;
  8655. var cloneValue = function (source, destinationObject) {
  8656. if (!source)
  8657. return null;
  8658. if (source instanceof BABYLON.Mesh) {
  8659. return null;
  8660. }
  8661. if (source instanceof BABYLON.SubMesh) {
  8662. return source.clone(destinationObject);
  8663. }
  8664. else if (source.clone) {
  8665. return source.clone();
  8666. }
  8667. return null;
  8668. };
  8669. var Tools = /** @class */ (function () {
  8670. function Tools() {
  8671. }
  8672. /**
  8673. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8674. * @param u defines the coordinate on X axis
  8675. * @param v defines the coordinate on Y axis
  8676. * @param width defines the width of the source data
  8677. * @param height defines the height of the source data
  8678. * @param pixels defines the source byte array
  8679. * @param color defines the output color
  8680. */
  8681. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8682. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8683. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8684. var position = (wrappedU + wrappedV * width) * 4;
  8685. color.r = pixels[position] / 255;
  8686. color.g = pixels[position + 1] / 255;
  8687. color.b = pixels[position + 2] / 255;
  8688. color.a = pixels[position + 3] / 255;
  8689. };
  8690. /**
  8691. * Interpolates between a and b via alpha
  8692. * @param a The lower value (returned when alpha = 0)
  8693. * @param b The upper value (returned when alpha = 1)
  8694. * @param alpha The interpolation-factor
  8695. * @return The mixed value
  8696. */
  8697. Tools.Mix = function (a, b, alpha) {
  8698. return a * (1 - alpha) + b * alpha;
  8699. };
  8700. Tools.Instantiate = function (className) {
  8701. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8702. return Tools.RegisteredExternalClasses[className];
  8703. }
  8704. var arr = className.split(".");
  8705. var fn = (window || this);
  8706. for (var i = 0, len = arr.length; i < len; i++) {
  8707. fn = fn[arr[i]];
  8708. }
  8709. if (typeof fn !== "function") {
  8710. return null;
  8711. }
  8712. return fn;
  8713. };
  8714. /**
  8715. * Provides a slice function that will work even on IE
  8716. * @param data defines the array to slice
  8717. * @param start defines the start of the data (optional)
  8718. * @param end defines the end of the data (optional)
  8719. * @returns the new sliced array
  8720. */
  8721. Tools.Slice = function (data, start, end) {
  8722. if (data.slice) {
  8723. return data.slice(start, end);
  8724. }
  8725. return Array.prototype.slice.call(data, start, end);
  8726. };
  8727. Tools.SetImmediate = function (action) {
  8728. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8729. window.setImmediate(action);
  8730. }
  8731. else {
  8732. setTimeout(action, 1);
  8733. }
  8734. };
  8735. Tools.IsExponentOfTwo = function (value) {
  8736. var count = 1;
  8737. do {
  8738. count *= 2;
  8739. } while (count < value);
  8740. return count === value;
  8741. };
  8742. /**
  8743. * Returns the nearest 32-bit single precision float representation of a Number
  8744. * @param value A Number. If the parameter is of a different type, it will get converted
  8745. * to a number or to NaN if it cannot be converted
  8746. * @returns number
  8747. */
  8748. Tools.FloatRound = function (value) {
  8749. if (Math.fround) {
  8750. return Math.fround(value);
  8751. }
  8752. return (Tools._tmpFloatArray[0] = value);
  8753. };
  8754. /**
  8755. * Find the next highest power of two.
  8756. * @param x Number to start search from.
  8757. * @return Next highest power of two.
  8758. */
  8759. Tools.CeilingPOT = function (x) {
  8760. x--;
  8761. x |= x >> 1;
  8762. x |= x >> 2;
  8763. x |= x >> 4;
  8764. x |= x >> 8;
  8765. x |= x >> 16;
  8766. x++;
  8767. return x;
  8768. };
  8769. /**
  8770. * Find the next lowest power of two.
  8771. * @param x Number to start search from.
  8772. * @return Next lowest power of two.
  8773. */
  8774. Tools.FloorPOT = function (x) {
  8775. x = x | (x >> 1);
  8776. x = x | (x >> 2);
  8777. x = x | (x >> 4);
  8778. x = x | (x >> 8);
  8779. x = x | (x >> 16);
  8780. return x - (x >> 1);
  8781. };
  8782. /**
  8783. * Find the nearest power of two.
  8784. * @param x Number to start search from.
  8785. * @return Next nearest power of two.
  8786. */
  8787. Tools.NearestPOT = function (x) {
  8788. var c = Tools.CeilingPOT(x);
  8789. var f = Tools.FloorPOT(x);
  8790. return (c - x) > (x - f) ? f : c;
  8791. };
  8792. Tools.GetExponentOfTwo = function (value, max, mode) {
  8793. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8794. var pot;
  8795. switch (mode) {
  8796. case BABYLON.Engine.SCALEMODE_FLOOR:
  8797. pot = Tools.FloorPOT(value);
  8798. break;
  8799. case BABYLON.Engine.SCALEMODE_NEAREST:
  8800. pot = Tools.NearestPOT(value);
  8801. break;
  8802. case BABYLON.Engine.SCALEMODE_CEILING:
  8803. default:
  8804. pot = Tools.CeilingPOT(value);
  8805. break;
  8806. }
  8807. return Math.min(pot, max);
  8808. };
  8809. Tools.GetFilename = function (path) {
  8810. var index = path.lastIndexOf("/");
  8811. if (index < 0)
  8812. return path;
  8813. return path.substring(index + 1);
  8814. };
  8815. /**
  8816. * Extracts the "folder" part of a path (everything before the filename).
  8817. * @param uri The URI to extract the info from
  8818. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8819. * @returns The "folder" part of the path
  8820. */
  8821. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8822. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8823. var index = uri.lastIndexOf("/");
  8824. if (index < 0) {
  8825. if (returnUnchangedIfNoSlash) {
  8826. return uri;
  8827. }
  8828. return "";
  8829. }
  8830. return uri.substring(0, index + 1);
  8831. };
  8832. Tools.GetDOMTextContent = function (element) {
  8833. var result = "";
  8834. var child = element.firstChild;
  8835. while (child) {
  8836. if (child.nodeType === 3) {
  8837. result += child.textContent;
  8838. }
  8839. child = child.nextSibling;
  8840. }
  8841. return result;
  8842. };
  8843. Tools.ToDegrees = function (angle) {
  8844. return angle * 180 / Math.PI;
  8845. };
  8846. Tools.ToRadians = function (angle) {
  8847. return angle * Math.PI / 180;
  8848. };
  8849. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8850. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8851. var output = "";
  8852. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8853. var i = 0;
  8854. var bytes = new Uint8Array(buffer);
  8855. while (i < bytes.length) {
  8856. chr1 = bytes[i++];
  8857. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8858. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8859. enc1 = chr1 >> 2;
  8860. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8861. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8862. enc4 = chr3 & 63;
  8863. if (isNaN(chr2)) {
  8864. enc3 = enc4 = 64;
  8865. }
  8866. else if (isNaN(chr3)) {
  8867. enc4 = 64;
  8868. }
  8869. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8870. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8871. }
  8872. return "data:image/png;base64," + output;
  8873. };
  8874. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8875. if (bias === void 0) { bias = null; }
  8876. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8877. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8878. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8879. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8880. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8881. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8882. }
  8883. if (bias) {
  8884. minimum.x -= minimum.x * bias.x + bias.y;
  8885. minimum.y -= minimum.y * bias.x + bias.y;
  8886. minimum.z -= minimum.z * bias.x + bias.y;
  8887. maximum.x += maximum.x * bias.x + bias.y;
  8888. maximum.y += maximum.y * bias.x + bias.y;
  8889. maximum.z += maximum.z * bias.x + bias.y;
  8890. }
  8891. return {
  8892. minimum: minimum,
  8893. maximum: maximum
  8894. };
  8895. };
  8896. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8897. if (bias === void 0) { bias = null; }
  8898. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8899. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8900. if (!stride) {
  8901. stride = 3;
  8902. }
  8903. for (var index = start; index < start + count; index++) {
  8904. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8905. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8906. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8907. }
  8908. if (bias) {
  8909. minimum.x -= minimum.x * bias.x + bias.y;
  8910. minimum.y -= minimum.y * bias.x + bias.y;
  8911. minimum.z -= minimum.z * bias.x + bias.y;
  8912. maximum.x += maximum.x * bias.x + bias.y;
  8913. maximum.y += maximum.y * bias.x + bias.y;
  8914. maximum.z += maximum.z * bias.x + bias.y;
  8915. }
  8916. return {
  8917. minimum: minimum,
  8918. maximum: maximum
  8919. };
  8920. };
  8921. Tools.Vector2ArrayFeeder = function (array) {
  8922. return function (index) {
  8923. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8924. var length = isFloatArray ? array.length / 2 : array.length;
  8925. if (index >= length) {
  8926. return null;
  8927. }
  8928. if (isFloatArray) {
  8929. var fa = array;
  8930. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8931. }
  8932. var a = array;
  8933. return a[index];
  8934. };
  8935. };
  8936. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8937. if (bias === void 0) { bias = null; }
  8938. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8939. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8940. var i = 0;
  8941. var cur = feeder(i++);
  8942. while (cur) {
  8943. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8944. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8945. cur = feeder(i++);
  8946. }
  8947. if (bias) {
  8948. minimum.x -= minimum.x * bias.x + bias.y;
  8949. minimum.y -= minimum.y * bias.x + bias.y;
  8950. maximum.x += maximum.x * bias.x + bias.y;
  8951. maximum.y += maximum.y * bias.x + bias.y;
  8952. }
  8953. return {
  8954. minimum: minimum,
  8955. maximum: maximum
  8956. };
  8957. };
  8958. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8959. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8960. return null;
  8961. return Array.isArray(obj) ? obj : [obj];
  8962. };
  8963. // Misc.
  8964. Tools.GetPointerPrefix = function () {
  8965. var eventPrefix = "pointer";
  8966. // Check if pointer events are supported
  8967. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8968. eventPrefix = "mouse";
  8969. }
  8970. return eventPrefix;
  8971. };
  8972. /**
  8973. * @param func - the function to be called
  8974. * @param requester - the object that will request the next frame. Falls back to window.
  8975. */
  8976. Tools.QueueNewFrame = function (func, requester) {
  8977. if (!Tools.IsWindowObjectExist()) {
  8978. return setTimeout(func, 16);
  8979. }
  8980. if (!requester) {
  8981. requester = window;
  8982. }
  8983. if (requester.requestAnimationFrame) {
  8984. return requester.requestAnimationFrame(func);
  8985. }
  8986. else if (requester.msRequestAnimationFrame) {
  8987. return requester.msRequestAnimationFrame(func);
  8988. }
  8989. else if (requester.webkitRequestAnimationFrame) {
  8990. return requester.webkitRequestAnimationFrame(func);
  8991. }
  8992. else if (requester.mozRequestAnimationFrame) {
  8993. return requester.mozRequestAnimationFrame(func);
  8994. }
  8995. else if (requester.oRequestAnimationFrame) {
  8996. return requester.oRequestAnimationFrame(func);
  8997. }
  8998. else {
  8999. return window.setTimeout(func, 16);
  9000. }
  9001. };
  9002. Tools.RequestFullscreen = function (element) {
  9003. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9004. if (!requestFunction)
  9005. return;
  9006. requestFunction.call(element);
  9007. };
  9008. Tools.ExitFullscreen = function () {
  9009. if (document.exitFullscreen) {
  9010. document.exitFullscreen();
  9011. }
  9012. else if (document.mozCancelFullScreen) {
  9013. document.mozCancelFullScreen();
  9014. }
  9015. else if (document.webkitCancelFullScreen) {
  9016. document.webkitCancelFullScreen();
  9017. }
  9018. else if (document.msCancelFullScreen) {
  9019. document.msCancelFullScreen();
  9020. }
  9021. };
  9022. Tools.SetCorsBehavior = function (url, element) {
  9023. if (url && url.indexOf("data:") === 0) {
  9024. return;
  9025. }
  9026. if (Tools.CorsBehavior) {
  9027. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9028. element.crossOrigin = Tools.CorsBehavior;
  9029. }
  9030. else {
  9031. var result = Tools.CorsBehavior(url);
  9032. if (result) {
  9033. element.crossOrigin = result;
  9034. }
  9035. }
  9036. }
  9037. };
  9038. // External files
  9039. Tools.CleanUrl = function (url) {
  9040. url = url.replace(/#/mg, "%23");
  9041. return url;
  9042. };
  9043. /**
  9044. * Loads an image as an HTMLImageElement.
  9045. * @param input url string, ArrayBuffer, or Blob to load
  9046. * @param onLoad callback called when the image successfully loads
  9047. * @param onError callback called when the image fails to load
  9048. * @param database database for caching
  9049. * @returns the HTMLImageElement of the loaded image
  9050. */
  9051. Tools.LoadImage = function (input, onLoad, onError, database) {
  9052. var url;
  9053. var usingObjectURL = false;
  9054. if (input instanceof ArrayBuffer) {
  9055. url = URL.createObjectURL(new Blob([input]));
  9056. usingObjectURL = true;
  9057. }
  9058. else if (input instanceof Blob) {
  9059. url = URL.createObjectURL(input);
  9060. usingObjectURL = true;
  9061. }
  9062. else {
  9063. url = Tools.CleanUrl(input);
  9064. url = Tools.PreprocessUrl(input);
  9065. }
  9066. var img = new Image();
  9067. Tools.SetCorsBehavior(url, img);
  9068. var loadHandler = function () {
  9069. if (usingObjectURL && img.src) {
  9070. URL.revokeObjectURL(img.src);
  9071. }
  9072. img.removeEventListener("load", loadHandler);
  9073. img.removeEventListener("error", errorHandler);
  9074. onLoad(img);
  9075. };
  9076. var errorHandler = function (err) {
  9077. if (usingObjectURL && img.src) {
  9078. URL.revokeObjectURL(img.src);
  9079. }
  9080. img.removeEventListener("load", loadHandler);
  9081. img.removeEventListener("error", errorHandler);
  9082. Tools.Error("Error while trying to load image: " + input);
  9083. if (onError) {
  9084. onError("Error while trying to load image: " + input, err);
  9085. }
  9086. };
  9087. img.addEventListener("load", loadHandler);
  9088. img.addEventListener("error", errorHandler);
  9089. var noIndexedDB = function () {
  9090. img.src = url;
  9091. };
  9092. var loadFromIndexedDB = function () {
  9093. if (database) {
  9094. database.loadImageFromDB(url, img);
  9095. }
  9096. };
  9097. //ANY database to do!
  9098. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9099. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9100. }
  9101. else {
  9102. if (url.indexOf("file:") !== -1) {
  9103. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9104. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9105. try {
  9106. var blobURL;
  9107. try {
  9108. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9109. }
  9110. catch (ex) {
  9111. // Chrome doesn't support oneTimeOnly parameter
  9112. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9113. }
  9114. img.src = blobURL;
  9115. usingObjectURL = true;
  9116. }
  9117. catch (e) {
  9118. img.src = "";
  9119. }
  9120. return img;
  9121. }
  9122. }
  9123. noIndexedDB();
  9124. }
  9125. return img;
  9126. };
  9127. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9128. url = Tools.CleanUrl(url);
  9129. url = Tools.PreprocessUrl(url);
  9130. // If file and file input are set
  9131. if (url.indexOf("file:") !== -1) {
  9132. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9133. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9134. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9135. }
  9136. }
  9137. var loadUrl = Tools.BaseUrl + url;
  9138. var aborted = false;
  9139. var fileRequest = {
  9140. onCompleteObservable: new BABYLON.Observable(),
  9141. abort: function () { return aborted = true; },
  9142. };
  9143. var requestFile = function () {
  9144. var request = new XMLHttpRequest();
  9145. var retryHandle = null;
  9146. fileRequest.abort = function () {
  9147. aborted = true;
  9148. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9149. request.abort();
  9150. }
  9151. if (retryHandle !== null) {
  9152. clearTimeout(retryHandle);
  9153. retryHandle = null;
  9154. }
  9155. };
  9156. var retryLoop = function (retryIndex) {
  9157. request.open('GET', loadUrl, true);
  9158. if (useArrayBuffer) {
  9159. request.responseType = "arraybuffer";
  9160. }
  9161. if (onProgress) {
  9162. request.addEventListener("progress", onProgress);
  9163. }
  9164. var onLoadEnd = function () {
  9165. request.removeEventListener("loadend", onLoadEnd);
  9166. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9167. fileRequest.onCompleteObservable.clear();
  9168. };
  9169. request.addEventListener("loadend", onLoadEnd);
  9170. var onReadyStateChange = function () {
  9171. if (aborted) {
  9172. return;
  9173. }
  9174. // In case of undefined state in some browsers.
  9175. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9176. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9177. request.removeEventListener("readystatechange", onReadyStateChange);
  9178. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9179. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9180. return;
  9181. }
  9182. var retryStrategy = Tools.DefaultRetryStrategy;
  9183. if (retryStrategy) {
  9184. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9185. if (waitTime !== -1) {
  9186. // Prevent the request from completing for retry.
  9187. request.removeEventListener("loadend", onLoadEnd);
  9188. request = new XMLHttpRequest();
  9189. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9190. return;
  9191. }
  9192. }
  9193. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9194. if (onError) {
  9195. onError(request, e);
  9196. }
  9197. else {
  9198. throw e;
  9199. }
  9200. }
  9201. };
  9202. request.addEventListener("readystatechange", onReadyStateChange);
  9203. request.send();
  9204. };
  9205. retryLoop(0);
  9206. };
  9207. // Caching all files
  9208. if (database && database.enableSceneOffline) {
  9209. var noIndexedDB_1 = function (request) {
  9210. if (request && request.status > 400) {
  9211. if (onError) {
  9212. onError(request);
  9213. }
  9214. }
  9215. else {
  9216. if (!aborted) {
  9217. requestFile();
  9218. }
  9219. }
  9220. };
  9221. var loadFromIndexedDB = function () {
  9222. // TODO: database needs to support aborting and should return a IFileRequest
  9223. if (aborted) {
  9224. return;
  9225. }
  9226. if (database) {
  9227. database.loadFileFromDB(url, function (data) {
  9228. if (!aborted) {
  9229. onSuccess(data);
  9230. }
  9231. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9232. }, onProgress ? function (event) {
  9233. if (!aborted) {
  9234. onProgress(event);
  9235. }
  9236. } : undefined, noIndexedDB_1, useArrayBuffer);
  9237. }
  9238. };
  9239. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9240. }
  9241. else {
  9242. requestFile();
  9243. }
  9244. return fileRequest;
  9245. };
  9246. /**
  9247. * Load a script (identified by an url). When the url returns, the
  9248. * content of this file is added into a new script element, attached to the DOM (body element)
  9249. */
  9250. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9251. if (!Tools.IsWindowObjectExist()) {
  9252. return;
  9253. }
  9254. var head = document.getElementsByTagName('head')[0];
  9255. var script = document.createElement('script');
  9256. script.type = 'text/javascript';
  9257. script.src = scriptUrl;
  9258. script.onload = function () {
  9259. if (onSuccess) {
  9260. onSuccess();
  9261. }
  9262. };
  9263. script.onerror = function (e) {
  9264. if (onError) {
  9265. onError("Unable to load script '" + scriptUrl + "'", e);
  9266. }
  9267. };
  9268. head.appendChild(script);
  9269. };
  9270. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9271. var reader = new FileReader();
  9272. var request = {
  9273. onCompleteObservable: new BABYLON.Observable(),
  9274. abort: function () { return reader.abort(); },
  9275. };
  9276. reader.onloadend = function (e) {
  9277. request.onCompleteObservable.notifyObservers(request);
  9278. };
  9279. reader.onload = function (e) {
  9280. //target doesn't have result from ts 1.3
  9281. callback(e.target['result']);
  9282. };
  9283. reader.onprogress = progressCallback;
  9284. reader.readAsDataURL(fileToLoad);
  9285. return request;
  9286. };
  9287. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9288. var reader = new FileReader();
  9289. var request = {
  9290. onCompleteObservable: new BABYLON.Observable(),
  9291. abort: function () { return reader.abort(); },
  9292. };
  9293. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9294. reader.onerror = function (e) {
  9295. Tools.Log("Error while reading file: " + fileToLoad.name);
  9296. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9297. };
  9298. reader.onload = function (e) {
  9299. //target doesn't have result from ts 1.3
  9300. callback(e.target['result']);
  9301. };
  9302. if (progressCallBack) {
  9303. reader.onprogress = progressCallBack;
  9304. }
  9305. if (!useArrayBuffer) {
  9306. // Asynchronous read
  9307. reader.readAsText(fileToLoad);
  9308. }
  9309. else {
  9310. reader.readAsArrayBuffer(fileToLoad);
  9311. }
  9312. return request;
  9313. };
  9314. //returns a downloadable url to a file content.
  9315. Tools.FileAsURL = function (content) {
  9316. var fileBlob = new Blob([content]);
  9317. var url = window.URL || window.webkitURL;
  9318. var link = url.createObjectURL(fileBlob);
  9319. return link;
  9320. };
  9321. // Misc.
  9322. Tools.Format = function (value, decimals) {
  9323. if (decimals === void 0) { decimals = 2; }
  9324. return value.toFixed(decimals);
  9325. };
  9326. Tools.CheckExtends = function (v, min, max) {
  9327. if (v.x < min.x)
  9328. min.x = v.x;
  9329. if (v.y < min.y)
  9330. min.y = v.y;
  9331. if (v.z < min.z)
  9332. min.z = v.z;
  9333. if (v.x > max.x)
  9334. max.x = v.x;
  9335. if (v.y > max.y)
  9336. max.y = v.y;
  9337. if (v.z > max.z)
  9338. max.z = v.z;
  9339. };
  9340. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9341. for (var prop in source) {
  9342. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9343. continue;
  9344. }
  9345. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9346. continue;
  9347. }
  9348. var sourceValue = source[prop];
  9349. var typeOfSourceValue = typeof sourceValue;
  9350. if (typeOfSourceValue === "function") {
  9351. continue;
  9352. }
  9353. try {
  9354. if (typeOfSourceValue === "object") {
  9355. if (sourceValue instanceof Array) {
  9356. destination[prop] = [];
  9357. if (sourceValue.length > 0) {
  9358. if (typeof sourceValue[0] == "object") {
  9359. for (var index = 0; index < sourceValue.length; index++) {
  9360. var clonedValue = cloneValue(sourceValue[index], destination);
  9361. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9362. destination[prop].push(clonedValue);
  9363. }
  9364. }
  9365. }
  9366. else {
  9367. destination[prop] = sourceValue.slice(0);
  9368. }
  9369. }
  9370. }
  9371. else {
  9372. destination[prop] = cloneValue(sourceValue, destination);
  9373. }
  9374. }
  9375. else {
  9376. destination[prop] = sourceValue;
  9377. }
  9378. }
  9379. catch (e) {
  9380. // Just ignore error (it could be because of a read-only property)
  9381. }
  9382. }
  9383. };
  9384. Tools.IsEmpty = function (obj) {
  9385. for (var i in obj) {
  9386. if (obj.hasOwnProperty(i)) {
  9387. return false;
  9388. }
  9389. }
  9390. return true;
  9391. };
  9392. Tools.RegisterTopRootEvents = function (events) {
  9393. for (var index = 0; index < events.length; index++) {
  9394. var event = events[index];
  9395. window.addEventListener(event.name, event.handler, false);
  9396. try {
  9397. if (window.parent) {
  9398. window.parent.addEventListener(event.name, event.handler, false);
  9399. }
  9400. }
  9401. catch (e) {
  9402. // Silently fails...
  9403. }
  9404. }
  9405. };
  9406. Tools.UnregisterTopRootEvents = function (events) {
  9407. for (var index = 0; index < events.length; index++) {
  9408. var event = events[index];
  9409. window.removeEventListener(event.name, event.handler);
  9410. try {
  9411. if (window.parent) {
  9412. window.parent.removeEventListener(event.name, event.handler);
  9413. }
  9414. }
  9415. catch (e) {
  9416. // Silently fails...
  9417. }
  9418. }
  9419. };
  9420. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9421. if (mimeType === void 0) { mimeType = "image/png"; }
  9422. // Read the contents of the framebuffer
  9423. var numberOfChannelsByLine = width * 4;
  9424. var halfHeight = height / 2;
  9425. //Reading datas from WebGL
  9426. var data = engine.readPixels(0, 0, width, height);
  9427. //To flip image on Y axis.
  9428. for (var i = 0; i < halfHeight; i++) {
  9429. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9430. var currentCell = j + i * numberOfChannelsByLine;
  9431. var targetLine = height - i - 1;
  9432. var targetCell = j + targetLine * numberOfChannelsByLine;
  9433. var temp = data[currentCell];
  9434. data[currentCell] = data[targetCell];
  9435. data[targetCell] = temp;
  9436. }
  9437. }
  9438. // Create a 2D canvas to store the result
  9439. if (!screenshotCanvas) {
  9440. screenshotCanvas = document.createElement('canvas');
  9441. }
  9442. screenshotCanvas.width = width;
  9443. screenshotCanvas.height = height;
  9444. var context = screenshotCanvas.getContext('2d');
  9445. if (context) {
  9446. // Copy the pixels to a 2D canvas
  9447. var imageData = context.createImageData(width, height);
  9448. var castData = (imageData.data);
  9449. castData.set(data);
  9450. context.putImageData(imageData, 0, 0);
  9451. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9452. }
  9453. };
  9454. /**
  9455. * Converts the canvas data to blob.
  9456. * This acts as a polyfill for browsers not supporting the to blob function.
  9457. * @param canvas Defines the canvas to extract the data from
  9458. * @param successCallback Defines the callback triggered once the data are available
  9459. * @param mimeType Defines the mime type of the result
  9460. */
  9461. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9462. if (mimeType === void 0) { mimeType = "image/png"; }
  9463. // We need HTMLCanvasElement.toBlob for HD screenshots
  9464. if (!canvas.toBlob) {
  9465. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9466. canvas.toBlob = function (callback, type, quality) {
  9467. var _this = this;
  9468. setTimeout(function () {
  9469. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9470. for (var i = 0; i < len; i++) {
  9471. arr[i] = binStr.charCodeAt(i);
  9472. }
  9473. callback(new Blob([arr]));
  9474. });
  9475. };
  9476. }
  9477. canvas.toBlob(function (blob) {
  9478. successCallback(blob);
  9479. }, mimeType);
  9480. };
  9481. /**
  9482. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9483. * @param successCallback Defines the callback triggered once the data are available
  9484. * @param mimeType Defines the mime type of the result
  9485. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9486. */
  9487. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9488. if (mimeType === void 0) { mimeType = "image/png"; }
  9489. if (successCallback) {
  9490. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9491. successCallback(base64Image);
  9492. }
  9493. else {
  9494. this.ToBlob(screenshotCanvas, function (blob) {
  9495. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9496. if (("download" in document.createElement("a"))) {
  9497. if (!fileName) {
  9498. var date = new Date();
  9499. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9500. fileName = "screenshot_" + stringDate + ".png";
  9501. }
  9502. Tools.Download(blob, fileName);
  9503. }
  9504. else {
  9505. var url = URL.createObjectURL(blob);
  9506. var newWindow = window.open("");
  9507. if (!newWindow)
  9508. return;
  9509. var img = newWindow.document.createElement("img");
  9510. img.onload = function () {
  9511. // no longer need to read the blob so it's revoked
  9512. URL.revokeObjectURL(url);
  9513. };
  9514. img.src = url;
  9515. newWindow.document.body.appendChild(img);
  9516. }
  9517. }, mimeType);
  9518. }
  9519. };
  9520. /**
  9521. * Downloads a blob in the browser
  9522. * @param blob defines the blob to download
  9523. * @param fileName defines the name of the downloaded file
  9524. */
  9525. Tools.Download = function (blob, fileName) {
  9526. if (navigator && navigator.msSaveBlob) {
  9527. navigator.msSaveBlob(blob, fileName);
  9528. return;
  9529. }
  9530. var url = window.URL.createObjectURL(blob);
  9531. var a = document.createElement("a");
  9532. document.body.appendChild(a);
  9533. a.style.display = "none";
  9534. a.href = url;
  9535. a.download = fileName;
  9536. a.addEventListener("click", function () {
  9537. if (a.parentElement) {
  9538. a.parentElement.removeChild(a);
  9539. }
  9540. });
  9541. a.click();
  9542. window.URL.revokeObjectURL(url);
  9543. };
  9544. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9545. if (mimeType === void 0) { mimeType = "image/png"; }
  9546. var width;
  9547. var height;
  9548. // If a precision value is specified
  9549. if (size.precision) {
  9550. width = Math.round(engine.getRenderWidth() * size.precision);
  9551. height = Math.round(width / engine.getAspectRatio(camera));
  9552. }
  9553. else if (size.width && size.height) {
  9554. width = size.width;
  9555. height = size.height;
  9556. }
  9557. //If passing only width, computing height to keep display canvas ratio.
  9558. else if (size.width && !size.height) {
  9559. width = size.width;
  9560. height = Math.round(width / engine.getAspectRatio(camera));
  9561. }
  9562. //If passing only height, computing width to keep display canvas ratio.
  9563. else if (size.height && !size.width) {
  9564. height = size.height;
  9565. width = Math.round(height * engine.getAspectRatio(camera));
  9566. }
  9567. //Assuming here that "size" parameter is a number
  9568. else if (!isNaN(size)) {
  9569. height = size;
  9570. width = size;
  9571. }
  9572. else {
  9573. Tools.Error("Invalid 'size' parameter !");
  9574. return;
  9575. }
  9576. if (!screenshotCanvas) {
  9577. screenshotCanvas = document.createElement('canvas');
  9578. }
  9579. screenshotCanvas.width = width;
  9580. screenshotCanvas.height = height;
  9581. var renderContext = screenshotCanvas.getContext("2d");
  9582. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9583. var newWidth = width;
  9584. var newHeight = newWidth / ratio;
  9585. if (newHeight > height) {
  9586. newHeight = height;
  9587. newWidth = newHeight * ratio;
  9588. }
  9589. var offsetX = Math.max(0, width - newWidth) / 2;
  9590. var offsetY = Math.max(0, height - newHeight) / 2;
  9591. var renderingCanvas = engine.getRenderingCanvas();
  9592. if (renderContext && renderingCanvas) {
  9593. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9594. }
  9595. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9596. };
  9597. /**
  9598. * Generates an image screenshot from the specified camera.
  9599. *
  9600. * @param engine The engine to use for rendering
  9601. * @param camera The camera to use for rendering
  9602. * @param size This parameter can be set to a single number or to an object with the
  9603. * following (optional) properties: precision, width, height. If a single number is passed,
  9604. * it will be used for both width and height. If an object is passed, the screenshot size
  9605. * will be derived from the parameters. The precision property is a multiplier allowing
  9606. * rendering at a higher or lower resolution.
  9607. * @param successCallback The callback receives a single parameter which contains the
  9608. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9609. * src parameter of an <img> to display it.
  9610. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9611. * Check your browser for supported MIME types.
  9612. * @param samples Texture samples (default: 1)
  9613. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9614. * @param fileName A name for for the downloaded file.
  9615. * @constructor
  9616. */
  9617. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9618. if (mimeType === void 0) { mimeType = "image/png"; }
  9619. if (samples === void 0) { samples = 1; }
  9620. if (antialiasing === void 0) { antialiasing = false; }
  9621. var width;
  9622. var height;
  9623. //If a precision value is specified
  9624. if (size.precision) {
  9625. width = Math.round(engine.getRenderWidth() * size.precision);
  9626. height = Math.round(width / engine.getAspectRatio(camera));
  9627. size = { width: width, height: height };
  9628. }
  9629. else if (size.width && size.height) {
  9630. width = size.width;
  9631. height = size.height;
  9632. }
  9633. //If passing only width, computing height to keep display canvas ratio.
  9634. else if (size.width && !size.height) {
  9635. width = size.width;
  9636. height = Math.round(width / engine.getAspectRatio(camera));
  9637. size = { width: width, height: height };
  9638. }
  9639. //If passing only height, computing width to keep display canvas ratio.
  9640. else if (size.height && !size.width) {
  9641. height = size.height;
  9642. width = Math.round(height * engine.getAspectRatio(camera));
  9643. size = { width: width, height: height };
  9644. }
  9645. //Assuming here that "size" parameter is a number
  9646. else if (!isNaN(size)) {
  9647. height = size;
  9648. width = size;
  9649. }
  9650. else {
  9651. Tools.Error("Invalid 'size' parameter !");
  9652. return;
  9653. }
  9654. var scene = camera.getScene();
  9655. var previousCamera = null;
  9656. if (scene.activeCamera !== camera) {
  9657. previousCamera = scene.activeCamera;
  9658. scene.activeCamera = camera;
  9659. }
  9660. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9661. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9662. texture.renderList = null;
  9663. texture.samples = samples;
  9664. if (antialiasing) {
  9665. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9666. }
  9667. texture.onAfterRenderObservable.add(function () {
  9668. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9669. });
  9670. scene.incrementRenderId();
  9671. scene.resetCachedMaterial();
  9672. texture.render(true);
  9673. texture.dispose();
  9674. if (previousCamera) {
  9675. scene.activeCamera = previousCamera;
  9676. }
  9677. camera.getProjectionMatrix(true); // Force cache refresh;
  9678. };
  9679. // XHR response validator for local file scenario
  9680. Tools.ValidateXHRData = function (xhr, dataType) {
  9681. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9682. if (dataType === void 0) { dataType = 7; }
  9683. try {
  9684. if (dataType & 1) {
  9685. if (xhr.responseText && xhr.responseText.length > 0) {
  9686. return true;
  9687. }
  9688. else if (dataType === 1) {
  9689. return false;
  9690. }
  9691. }
  9692. if (dataType & 2) {
  9693. // Check header width and height since there is no "TGA" magic number
  9694. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9695. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9696. return true;
  9697. }
  9698. else if (dataType === 2) {
  9699. return false;
  9700. }
  9701. }
  9702. if (dataType & 4) {
  9703. // Check for the "DDS" magic number
  9704. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9705. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9706. return true;
  9707. }
  9708. else {
  9709. return false;
  9710. }
  9711. }
  9712. }
  9713. catch (e) {
  9714. // Global protection
  9715. }
  9716. return false;
  9717. };
  9718. /**
  9719. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9720. * Be aware Math.random() could cause collisions, but:
  9721. * "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"
  9722. */
  9723. Tools.RandomId = function () {
  9724. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9725. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9726. return v.toString(16);
  9727. });
  9728. };
  9729. /**
  9730. * Test if the given uri is a base64 string.
  9731. * @param uri The uri to test
  9732. * @return True if the uri is a base64 string or false otherwise.
  9733. */
  9734. Tools.IsBase64 = function (uri) {
  9735. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9736. };
  9737. /**
  9738. * Decode the given base64 uri.
  9739. * @param uri The uri to decode
  9740. * @return The decoded base64 data.
  9741. */
  9742. Tools.DecodeBase64 = function (uri) {
  9743. var decodedString = atob(uri.split(",")[1]);
  9744. var bufferLength = decodedString.length;
  9745. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9746. for (var i = 0; i < bufferLength; i++) {
  9747. bufferView[i] = decodedString.charCodeAt(i);
  9748. }
  9749. return bufferView.buffer;
  9750. };
  9751. Object.defineProperty(Tools, "NoneLogLevel", {
  9752. get: function () {
  9753. return Tools._NoneLogLevel;
  9754. },
  9755. enumerable: true,
  9756. configurable: true
  9757. });
  9758. Object.defineProperty(Tools, "MessageLogLevel", {
  9759. get: function () {
  9760. return Tools._MessageLogLevel;
  9761. },
  9762. enumerable: true,
  9763. configurable: true
  9764. });
  9765. Object.defineProperty(Tools, "WarningLogLevel", {
  9766. get: function () {
  9767. return Tools._WarningLogLevel;
  9768. },
  9769. enumerable: true,
  9770. configurable: true
  9771. });
  9772. Object.defineProperty(Tools, "ErrorLogLevel", {
  9773. get: function () {
  9774. return Tools._ErrorLogLevel;
  9775. },
  9776. enumerable: true,
  9777. configurable: true
  9778. });
  9779. Object.defineProperty(Tools, "AllLogLevel", {
  9780. get: function () {
  9781. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9782. },
  9783. enumerable: true,
  9784. configurable: true
  9785. });
  9786. Tools._AddLogEntry = function (entry) {
  9787. Tools._LogCache = entry + Tools._LogCache;
  9788. if (Tools.OnNewCacheEntry) {
  9789. Tools.OnNewCacheEntry(entry);
  9790. }
  9791. };
  9792. Tools._FormatMessage = function (message) {
  9793. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9794. var date = new Date();
  9795. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9796. };
  9797. Tools._LogDisabled = function (message) {
  9798. // nothing to do
  9799. };
  9800. Tools._LogEnabled = function (message) {
  9801. var formattedMessage = Tools._FormatMessage(message);
  9802. console.log("BJS - " + formattedMessage);
  9803. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9804. Tools._AddLogEntry(entry);
  9805. };
  9806. Tools._WarnDisabled = function (message) {
  9807. // nothing to do
  9808. };
  9809. Tools._WarnEnabled = function (message) {
  9810. var formattedMessage = Tools._FormatMessage(message);
  9811. console.warn("BJS - " + formattedMessage);
  9812. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9813. Tools._AddLogEntry(entry);
  9814. };
  9815. Tools._ErrorDisabled = function (message) {
  9816. // nothing to do
  9817. };
  9818. Tools._ErrorEnabled = function (message) {
  9819. Tools.errorsCount++;
  9820. var formattedMessage = Tools._FormatMessage(message);
  9821. console.error("BJS - " + formattedMessage);
  9822. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9823. Tools._AddLogEntry(entry);
  9824. };
  9825. Object.defineProperty(Tools, "LogCache", {
  9826. get: function () {
  9827. return Tools._LogCache;
  9828. },
  9829. enumerable: true,
  9830. configurable: true
  9831. });
  9832. Tools.ClearLogCache = function () {
  9833. Tools._LogCache = "";
  9834. Tools.errorsCount = 0;
  9835. };
  9836. Object.defineProperty(Tools, "LogLevels", {
  9837. set: function (level) {
  9838. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9839. Tools.Log = Tools._LogEnabled;
  9840. }
  9841. else {
  9842. Tools.Log = Tools._LogDisabled;
  9843. }
  9844. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9845. Tools.Warn = Tools._WarnEnabled;
  9846. }
  9847. else {
  9848. Tools.Warn = Tools._WarnDisabled;
  9849. }
  9850. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9851. Tools.Error = Tools._ErrorEnabled;
  9852. }
  9853. else {
  9854. Tools.Error = Tools._ErrorDisabled;
  9855. }
  9856. },
  9857. enumerable: true,
  9858. configurable: true
  9859. });
  9860. /**
  9861. * Check if the loaded document was accessed via `file:`-Protocol.
  9862. * @returns boolean
  9863. */
  9864. Tools.IsFileURL = function () {
  9865. return location.protocol === "file:";
  9866. };
  9867. Tools.IsWindowObjectExist = function () {
  9868. return (typeof window) !== "undefined";
  9869. };
  9870. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9871. get: function () {
  9872. return Tools._PerformanceNoneLogLevel;
  9873. },
  9874. enumerable: true,
  9875. configurable: true
  9876. });
  9877. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9878. get: function () {
  9879. return Tools._PerformanceUserMarkLogLevel;
  9880. },
  9881. enumerable: true,
  9882. configurable: true
  9883. });
  9884. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9885. get: function () {
  9886. return Tools._PerformanceConsoleLogLevel;
  9887. },
  9888. enumerable: true,
  9889. configurable: true
  9890. });
  9891. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9892. set: function (level) {
  9893. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9894. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9895. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9896. return;
  9897. }
  9898. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9899. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9900. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9901. return;
  9902. }
  9903. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9904. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9905. },
  9906. enumerable: true,
  9907. configurable: true
  9908. });
  9909. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9910. };
  9911. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9912. };
  9913. Tools._StartUserMark = function (counterName, condition) {
  9914. if (condition === void 0) { condition = true; }
  9915. if (!Tools._performance) {
  9916. if (!Tools.IsWindowObjectExist()) {
  9917. return;
  9918. }
  9919. Tools._performance = window.performance;
  9920. }
  9921. if (!condition || !Tools._performance.mark) {
  9922. return;
  9923. }
  9924. Tools._performance.mark(counterName + "-Begin");
  9925. };
  9926. Tools._EndUserMark = function (counterName, condition) {
  9927. if (condition === void 0) { condition = true; }
  9928. if (!condition || !Tools._performance.mark) {
  9929. return;
  9930. }
  9931. Tools._performance.mark(counterName + "-End");
  9932. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9933. };
  9934. Tools._StartPerformanceConsole = function (counterName, condition) {
  9935. if (condition === void 0) { condition = true; }
  9936. if (!condition) {
  9937. return;
  9938. }
  9939. Tools._StartUserMark(counterName, condition);
  9940. if (console.time) {
  9941. console.time(counterName);
  9942. }
  9943. };
  9944. Tools._EndPerformanceConsole = function (counterName, condition) {
  9945. if (condition === void 0) { condition = true; }
  9946. if (!condition) {
  9947. return;
  9948. }
  9949. Tools._EndUserMark(counterName, condition);
  9950. if (console.time) {
  9951. console.timeEnd(counterName);
  9952. }
  9953. };
  9954. Object.defineProperty(Tools, "Now", {
  9955. get: function () {
  9956. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9957. return window.performance.now();
  9958. }
  9959. return Date.now();
  9960. },
  9961. enumerable: true,
  9962. configurable: true
  9963. });
  9964. /**
  9965. * This method will return the name of the class used to create the instance of the given object.
  9966. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9967. * @param object the object to get the class name from
  9968. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9969. */
  9970. Tools.GetClassName = function (object, isType) {
  9971. if (isType === void 0) { isType = false; }
  9972. var name = null;
  9973. if (!isType && object.getClassName) {
  9974. name = object.getClassName();
  9975. }
  9976. else {
  9977. if (object instanceof Object) {
  9978. var classObj = isType ? object : Object.getPrototypeOf(object);
  9979. name = classObj.constructor["__bjsclassName__"];
  9980. }
  9981. if (!name) {
  9982. name = typeof object;
  9983. }
  9984. }
  9985. return name;
  9986. };
  9987. Tools.First = function (array, predicate) {
  9988. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9989. var el = array_1[_i];
  9990. if (predicate(el)) {
  9991. return el;
  9992. }
  9993. }
  9994. return null;
  9995. };
  9996. /**
  9997. * This method will return the name of the full name of the class, including its owning module (if any).
  9998. * 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).
  9999. * @param object the object to get the class name from
  10000. * @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.
  10001. */
  10002. Tools.getFullClassName = function (object, isType) {
  10003. if (isType === void 0) { isType = false; }
  10004. var className = null;
  10005. var moduleName = null;
  10006. if (!isType && object.getClassName) {
  10007. className = object.getClassName();
  10008. }
  10009. else {
  10010. if (object instanceof Object) {
  10011. var classObj = isType ? object : Object.getPrototypeOf(object);
  10012. className = classObj.constructor["__bjsclassName__"];
  10013. moduleName = classObj.constructor["__bjsmoduleName__"];
  10014. }
  10015. if (!className) {
  10016. className = typeof object;
  10017. }
  10018. }
  10019. if (!className) {
  10020. return null;
  10021. }
  10022. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10023. };
  10024. /**
  10025. * 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.
  10026. * @param array
  10027. */
  10028. Tools.arrayOrStringFeeder = function (array) {
  10029. return function (index) {
  10030. if (index >= array.length) {
  10031. return null;
  10032. }
  10033. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10034. if (val && val.getHashCode) {
  10035. val = val.getHashCode();
  10036. }
  10037. if (typeof val === "string") {
  10038. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10039. }
  10040. return val;
  10041. };
  10042. };
  10043. /**
  10044. * Compute the hashCode of a stream of number
  10045. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10046. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10047. * @return the hash code computed
  10048. */
  10049. Tools.hashCodeFromStream = function (feeder) {
  10050. // Based from here: http://stackoverflow.com/a/7616484/802124
  10051. var hash = 0;
  10052. var index = 0;
  10053. var chr = feeder(index++);
  10054. while (chr != null) {
  10055. hash = ((hash << 5) - hash) + chr;
  10056. hash |= 0; // Convert to 32bit integer
  10057. chr = feeder(index++);
  10058. }
  10059. return hash;
  10060. };
  10061. /**
  10062. * Returns a promise that resolves after the given amount of time.
  10063. * @param delay Number of milliseconds to delay
  10064. * @returns Promise that resolves after the given amount of time
  10065. */
  10066. Tools.DelayAsync = function (delay) {
  10067. return new Promise(function (resolve) {
  10068. setTimeout(function () {
  10069. resolve();
  10070. }, delay);
  10071. });
  10072. };
  10073. /**
  10074. * Gets the current gradient from an array of IValueGradient
  10075. * @param ratio defines the current ratio to get
  10076. * @param gradients defines the array of IValueGradient
  10077. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10078. */
  10079. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10080. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10081. var currentGradient = gradients[gradientIndex];
  10082. var nextGradient = gradients[gradientIndex + 1];
  10083. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10084. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10085. updateFunc(currentGradient, nextGradient, scale);
  10086. return;
  10087. }
  10088. }
  10089. // Use last index if over
  10090. var lastIndex = gradients.length - 1;
  10091. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10092. };
  10093. Tools.BaseUrl = "";
  10094. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10095. /**
  10096. * Default behaviour for cors in the application.
  10097. * It can be a string if the expected behavior is identical in the entire app.
  10098. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10099. */
  10100. Tools.CorsBehavior = "anonymous";
  10101. Tools.UseFallbackTexture = true;
  10102. /**
  10103. * Use this object to register external classes like custom textures or material
  10104. * to allow the laoders to instantiate them
  10105. */
  10106. Tools.RegisteredExternalClasses = {};
  10107. // Used in case of a texture loading problem
  10108. 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";
  10109. Tools._tmpFloatArray = new Float32Array(1);
  10110. Tools.PreprocessUrl = function (url) {
  10111. return url;
  10112. };
  10113. // Logs
  10114. Tools._NoneLogLevel = 0;
  10115. Tools._MessageLogLevel = 1;
  10116. Tools._WarningLogLevel = 2;
  10117. Tools._ErrorLogLevel = 4;
  10118. Tools._LogCache = "";
  10119. Tools.errorsCount = 0;
  10120. Tools.Log = Tools._LogEnabled;
  10121. Tools.Warn = Tools._WarnEnabled;
  10122. Tools.Error = Tools._ErrorEnabled;
  10123. // Performances
  10124. Tools._PerformanceNoneLogLevel = 0;
  10125. Tools._PerformanceUserMarkLogLevel = 1;
  10126. Tools._PerformanceConsoleLogLevel = 2;
  10127. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10128. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10129. return Tools;
  10130. }());
  10131. BABYLON.Tools = Tools;
  10132. /**
  10133. * This class is used to track a performance counter which is number based.
  10134. * The user has access to many properties which give statistics of different nature
  10135. *
  10136. * The implementer can track two kinds of Performance Counter: time and count
  10137. * 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.
  10138. * 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.
  10139. */
  10140. var PerfCounter = /** @class */ (function () {
  10141. function PerfCounter() {
  10142. this._startMonitoringTime = 0;
  10143. this._min = 0;
  10144. this._max = 0;
  10145. this._average = 0;
  10146. this._lastSecAverage = 0;
  10147. this._current = 0;
  10148. this._totalValueCount = 0;
  10149. this._totalAccumulated = 0;
  10150. this._lastSecAccumulated = 0;
  10151. this._lastSecTime = 0;
  10152. this._lastSecValueCount = 0;
  10153. }
  10154. Object.defineProperty(PerfCounter.prototype, "min", {
  10155. /**
  10156. * Returns the smallest value ever
  10157. */
  10158. get: function () {
  10159. return this._min;
  10160. },
  10161. enumerable: true,
  10162. configurable: true
  10163. });
  10164. Object.defineProperty(PerfCounter.prototype, "max", {
  10165. /**
  10166. * Returns the biggest value ever
  10167. */
  10168. get: function () {
  10169. return this._max;
  10170. },
  10171. enumerable: true,
  10172. configurable: true
  10173. });
  10174. Object.defineProperty(PerfCounter.prototype, "average", {
  10175. /**
  10176. * Returns the average value since the performance counter is running
  10177. */
  10178. get: function () {
  10179. return this._average;
  10180. },
  10181. enumerable: true,
  10182. configurable: true
  10183. });
  10184. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10185. /**
  10186. * Returns the average value of the last second the counter was monitored
  10187. */
  10188. get: function () {
  10189. return this._lastSecAverage;
  10190. },
  10191. enumerable: true,
  10192. configurable: true
  10193. });
  10194. Object.defineProperty(PerfCounter.prototype, "current", {
  10195. /**
  10196. * Returns the current value
  10197. */
  10198. get: function () {
  10199. return this._current;
  10200. },
  10201. enumerable: true,
  10202. configurable: true
  10203. });
  10204. Object.defineProperty(PerfCounter.prototype, "total", {
  10205. get: function () {
  10206. return this._totalAccumulated;
  10207. },
  10208. enumerable: true,
  10209. configurable: true
  10210. });
  10211. Object.defineProperty(PerfCounter.prototype, "count", {
  10212. get: function () {
  10213. return this._totalValueCount;
  10214. },
  10215. enumerable: true,
  10216. configurable: true
  10217. });
  10218. /**
  10219. * Call this method to start monitoring a new frame.
  10220. * 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.
  10221. */
  10222. PerfCounter.prototype.fetchNewFrame = function () {
  10223. this._totalValueCount++;
  10224. this._current = 0;
  10225. this._lastSecValueCount++;
  10226. };
  10227. /**
  10228. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10229. * @param newCount the count value to add to the monitored count
  10230. * @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.
  10231. */
  10232. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10233. if (!PerfCounter.Enabled) {
  10234. return;
  10235. }
  10236. this._current += newCount;
  10237. if (fetchResult) {
  10238. this._fetchResult();
  10239. }
  10240. };
  10241. /**
  10242. * Start monitoring this performance counter
  10243. */
  10244. PerfCounter.prototype.beginMonitoring = function () {
  10245. if (!PerfCounter.Enabled) {
  10246. return;
  10247. }
  10248. this._startMonitoringTime = Tools.Now;
  10249. };
  10250. /**
  10251. * Compute the time lapsed since the previous beginMonitoring() call.
  10252. * @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
  10253. */
  10254. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10255. if (newFrame === void 0) { newFrame = true; }
  10256. if (!PerfCounter.Enabled) {
  10257. return;
  10258. }
  10259. if (newFrame) {
  10260. this.fetchNewFrame();
  10261. }
  10262. var currentTime = Tools.Now;
  10263. this._current = currentTime - this._startMonitoringTime;
  10264. if (newFrame) {
  10265. this._fetchResult();
  10266. }
  10267. };
  10268. PerfCounter.prototype._fetchResult = function () {
  10269. this._totalAccumulated += this._current;
  10270. this._lastSecAccumulated += this._current;
  10271. // Min/Max update
  10272. this._min = Math.min(this._min, this._current);
  10273. this._max = Math.max(this._max, this._current);
  10274. this._average = this._totalAccumulated / this._totalValueCount;
  10275. // Reset last sec?
  10276. var now = Tools.Now;
  10277. if ((now - this._lastSecTime) > 1000) {
  10278. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10279. this._lastSecTime = now;
  10280. this._lastSecAccumulated = 0;
  10281. this._lastSecValueCount = 0;
  10282. }
  10283. };
  10284. PerfCounter.Enabled = true;
  10285. return PerfCounter;
  10286. }());
  10287. BABYLON.PerfCounter = PerfCounter;
  10288. /**
  10289. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10290. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10291. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10292. * @param name The name of the class, case should be preserved
  10293. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10294. */
  10295. function className(name, module) {
  10296. return function (target) {
  10297. target["__bjsclassName__"] = name;
  10298. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10299. };
  10300. }
  10301. BABYLON.className = className;
  10302. /**
  10303. * An implementation of a loop for asynchronous functions.
  10304. */
  10305. var AsyncLoop = /** @class */ (function () {
  10306. /**
  10307. * Constroctor.
  10308. * @param iterations the number of iterations.
  10309. * @param _fn the function to run each iteration
  10310. * @param _successCallback the callback that will be called upon succesful execution
  10311. * @param offset starting offset.
  10312. */
  10313. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10314. if (offset === void 0) { offset = 0; }
  10315. this.iterations = iterations;
  10316. this._fn = _fn;
  10317. this._successCallback = _successCallback;
  10318. this.index = offset - 1;
  10319. this._done = false;
  10320. }
  10321. /**
  10322. * Execute the next iteration. Must be called after the last iteration was finished.
  10323. */
  10324. AsyncLoop.prototype.executeNext = function () {
  10325. if (!this._done) {
  10326. if (this.index + 1 < this.iterations) {
  10327. ++this.index;
  10328. this._fn(this);
  10329. }
  10330. else {
  10331. this.breakLoop();
  10332. }
  10333. }
  10334. };
  10335. /**
  10336. * Break the loop and run the success callback.
  10337. */
  10338. AsyncLoop.prototype.breakLoop = function () {
  10339. this._done = true;
  10340. this._successCallback();
  10341. };
  10342. /**
  10343. * Helper function
  10344. */
  10345. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10346. if (offset === void 0) { offset = 0; }
  10347. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10348. loop.executeNext();
  10349. return loop;
  10350. };
  10351. /**
  10352. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10353. * @param iterations total number of iterations
  10354. * @param syncedIterations number of synchronous iterations in each async iteration.
  10355. * @param fn the function to call each iteration.
  10356. * @param callback a success call back that will be called when iterating stops.
  10357. * @param breakFunction a break condition (optional)
  10358. * @param timeout timeout settings for the setTimeout function. default - 0.
  10359. * @constructor
  10360. */
  10361. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10362. if (timeout === void 0) { timeout = 0; }
  10363. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10364. if (breakFunction && breakFunction())
  10365. loop.breakLoop();
  10366. else {
  10367. setTimeout(function () {
  10368. for (var i = 0; i < syncedIterations; ++i) {
  10369. var iteration = (loop.index * syncedIterations) + i;
  10370. if (iteration >= iterations)
  10371. break;
  10372. fn(iteration);
  10373. if (breakFunction && breakFunction()) {
  10374. loop.breakLoop();
  10375. break;
  10376. }
  10377. }
  10378. loop.executeNext();
  10379. }, timeout);
  10380. }
  10381. }, callback);
  10382. };
  10383. return AsyncLoop;
  10384. }());
  10385. BABYLON.AsyncLoop = AsyncLoop;
  10386. })(BABYLON || (BABYLON = {}));
  10387. //# sourceMappingURL=babylon.tools.js.map
  10388. var BABYLON;
  10389. (function (BABYLON) {
  10390. var PromiseStates;
  10391. (function (PromiseStates) {
  10392. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10393. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10394. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10395. })(PromiseStates || (PromiseStates = {}));
  10396. var FulFillmentAgregator = /** @class */ (function () {
  10397. function FulFillmentAgregator() {
  10398. this.count = 0;
  10399. this.target = 0;
  10400. this.results = [];
  10401. }
  10402. return FulFillmentAgregator;
  10403. }());
  10404. var InternalPromise = /** @class */ (function () {
  10405. function InternalPromise(resolver) {
  10406. var _this = this;
  10407. this._state = PromiseStates.Pending;
  10408. this._children = new Array();
  10409. this._rejectWasConsumed = false;
  10410. if (!resolver) {
  10411. return;
  10412. }
  10413. try {
  10414. resolver(function (value) {
  10415. _this._resolve(value);
  10416. }, function (reason) {
  10417. _this._reject(reason);
  10418. });
  10419. }
  10420. catch (e) {
  10421. this._reject(e);
  10422. }
  10423. }
  10424. Object.defineProperty(InternalPromise.prototype, "_result", {
  10425. get: function () {
  10426. return this._resultValue;
  10427. },
  10428. set: function (value) {
  10429. this._resultValue = value;
  10430. if (this._parent && this._parent._result === undefined) {
  10431. this._parent._result = value;
  10432. }
  10433. },
  10434. enumerable: true,
  10435. configurable: true
  10436. });
  10437. InternalPromise.prototype.catch = function (onRejected) {
  10438. return this.then(undefined, onRejected);
  10439. };
  10440. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10441. var _this = this;
  10442. var newPromise = new InternalPromise();
  10443. newPromise._onFulfilled = onFulfilled;
  10444. newPromise._onRejected = onRejected;
  10445. // Composition
  10446. this._children.push(newPromise);
  10447. newPromise._parent = this;
  10448. if (this._state !== PromiseStates.Pending) {
  10449. BABYLON.Tools.SetImmediate(function () {
  10450. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10451. var returnedValue = newPromise._resolve(_this._result);
  10452. if (returnedValue !== undefined && returnedValue !== null) {
  10453. if (returnedValue._state !== undefined) {
  10454. var returnedPromise = returnedValue;
  10455. newPromise._children.push(returnedPromise);
  10456. returnedPromise._parent = newPromise;
  10457. newPromise = returnedPromise;
  10458. }
  10459. else {
  10460. newPromise._result = returnedValue;
  10461. }
  10462. }
  10463. }
  10464. else {
  10465. newPromise._reject(_this._reason);
  10466. }
  10467. });
  10468. }
  10469. return newPromise;
  10470. };
  10471. InternalPromise.prototype._moveChildren = function (children) {
  10472. var _this = this;
  10473. var _a;
  10474. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10475. this._children.forEach(function (child) {
  10476. child._parent = _this;
  10477. });
  10478. if (this._state === PromiseStates.Fulfilled) {
  10479. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10480. var child = _b[_i];
  10481. child._resolve(this._result);
  10482. }
  10483. }
  10484. else if (this._state === PromiseStates.Rejected) {
  10485. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10486. var child = _d[_c];
  10487. child._reject(this._reason);
  10488. }
  10489. }
  10490. };
  10491. InternalPromise.prototype._resolve = function (value) {
  10492. try {
  10493. this._state = PromiseStates.Fulfilled;
  10494. var returnedValue = null;
  10495. if (this._onFulfilled) {
  10496. returnedValue = this._onFulfilled(value);
  10497. }
  10498. if (returnedValue !== undefined && returnedValue !== null) {
  10499. if (returnedValue._state !== undefined) {
  10500. // Transmit children
  10501. var returnedPromise = returnedValue;
  10502. returnedPromise._parent = this;
  10503. returnedPromise._moveChildren(this._children);
  10504. value = returnedPromise._result;
  10505. }
  10506. else {
  10507. value = returnedValue;
  10508. }
  10509. }
  10510. this._result = value;
  10511. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10512. var child = _a[_i];
  10513. child._resolve(value);
  10514. }
  10515. this._children.length = 0;
  10516. delete this._onFulfilled;
  10517. delete this._onRejected;
  10518. }
  10519. catch (e) {
  10520. this._reject(e, true);
  10521. }
  10522. };
  10523. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10524. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10525. this._state = PromiseStates.Rejected;
  10526. this._reason = reason;
  10527. if (this._onRejected && !onLocalThrow) {
  10528. try {
  10529. this._onRejected(reason);
  10530. this._rejectWasConsumed = true;
  10531. }
  10532. catch (e) {
  10533. reason = e;
  10534. }
  10535. }
  10536. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10537. var child = _a[_i];
  10538. if (this._rejectWasConsumed) {
  10539. child._resolve(null);
  10540. }
  10541. else {
  10542. child._reject(reason);
  10543. }
  10544. }
  10545. this._children.length = 0;
  10546. delete this._onFulfilled;
  10547. delete this._onRejected;
  10548. };
  10549. InternalPromise.resolve = function (value) {
  10550. var newPromise = new InternalPromise();
  10551. newPromise._resolve(value);
  10552. return newPromise;
  10553. };
  10554. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10555. promise.then(function (value) {
  10556. agregator.results[index] = value;
  10557. agregator.count++;
  10558. if (agregator.count === agregator.target) {
  10559. agregator.rootPromise._resolve(agregator.results);
  10560. }
  10561. return null;
  10562. }, function (reason) {
  10563. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10564. agregator.rootPromise._reject(reason);
  10565. }
  10566. });
  10567. };
  10568. InternalPromise.all = function (promises) {
  10569. var newPromise = new InternalPromise();
  10570. var agregator = new FulFillmentAgregator();
  10571. agregator.target = promises.length;
  10572. agregator.rootPromise = newPromise;
  10573. if (promises.length) {
  10574. for (var index = 0; index < promises.length; index++) {
  10575. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10576. }
  10577. }
  10578. else {
  10579. newPromise._resolve([]);
  10580. }
  10581. return newPromise;
  10582. };
  10583. InternalPromise.race = function (promises) {
  10584. var newPromise = new InternalPromise();
  10585. if (promises.length) {
  10586. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10587. var promise = promises_1[_i];
  10588. promise.then(function (value) {
  10589. if (newPromise) {
  10590. newPromise._resolve(value);
  10591. newPromise = null;
  10592. }
  10593. return null;
  10594. }, function (reason) {
  10595. if (newPromise) {
  10596. newPromise._reject(reason);
  10597. newPromise = null;
  10598. }
  10599. });
  10600. }
  10601. }
  10602. return newPromise;
  10603. };
  10604. return InternalPromise;
  10605. }());
  10606. /**
  10607. * Helper class that provides a small promise polyfill
  10608. */
  10609. var PromisePolyfill = /** @class */ (function () {
  10610. function PromisePolyfill() {
  10611. }
  10612. /**
  10613. * Static function used to check if the polyfill is required
  10614. * If this is the case then the function will inject the polyfill to window.Promise
  10615. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10616. */
  10617. PromisePolyfill.Apply = function (force) {
  10618. if (force === void 0) { force = false; }
  10619. if (force || typeof Promise === 'undefined') {
  10620. var root = window;
  10621. root.Promise = InternalPromise;
  10622. }
  10623. };
  10624. return PromisePolyfill;
  10625. }());
  10626. BABYLON.PromisePolyfill = PromisePolyfill;
  10627. })(BABYLON || (BABYLON = {}));
  10628. //# sourceMappingURL=babylon.promise.js.map
  10629. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10630. var BABYLON;
  10631. (function (BABYLON) {
  10632. /**
  10633. * Helper class to push actions to a pool of workers.
  10634. */
  10635. var WorkerPool = /** @class */ (function () {
  10636. /**
  10637. * Constructor
  10638. * @param workers Array of workers to use for actions
  10639. */
  10640. function WorkerPool(workers) {
  10641. this._pendingActions = new Array();
  10642. this._workerInfos = workers.map(function (worker) { return ({
  10643. worker: worker,
  10644. active: false
  10645. }); });
  10646. }
  10647. /**
  10648. * Terminates all workers and clears any pending actions.
  10649. */
  10650. WorkerPool.prototype.dispose = function () {
  10651. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10652. var workerInfo = _a[_i];
  10653. workerInfo.worker.terminate();
  10654. }
  10655. delete this._workerInfos;
  10656. delete this._pendingActions;
  10657. };
  10658. /**
  10659. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10660. * pended until a worker has completed its action.
  10661. * @param action The action to perform. Call onComplete when the action is complete.
  10662. */
  10663. WorkerPool.prototype.push = function (action) {
  10664. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10665. var workerInfo = _a[_i];
  10666. if (!workerInfo.active) {
  10667. this._execute(workerInfo, action);
  10668. return;
  10669. }
  10670. }
  10671. this._pendingActions.push(action);
  10672. };
  10673. WorkerPool.prototype._execute = function (workerInfo, action) {
  10674. var _this = this;
  10675. workerInfo.active = true;
  10676. action(workerInfo.worker, function () {
  10677. workerInfo.active = false;
  10678. var nextAction = _this._pendingActions.shift();
  10679. if (nextAction) {
  10680. _this._execute(workerInfo, nextAction);
  10681. }
  10682. });
  10683. };
  10684. return WorkerPool;
  10685. }());
  10686. BABYLON.WorkerPool = WorkerPool;
  10687. })(BABYLON || (BABYLON = {}));
  10688. //# sourceMappingURL=babylon.workerPool.js.map
  10689. var BABYLON;
  10690. (function (BABYLON) {
  10691. /**
  10692. * @hidden
  10693. **/
  10694. var _AlphaState = /** @class */ (function () {
  10695. /**
  10696. * Initializes the state.
  10697. */
  10698. function _AlphaState() {
  10699. this._isAlphaBlendDirty = false;
  10700. this._isBlendFunctionParametersDirty = false;
  10701. this._isBlendEquationParametersDirty = false;
  10702. this._isBlendConstantsDirty = false;
  10703. this._alphaBlend = false;
  10704. this._blendFunctionParameters = new Array(4);
  10705. this._blendEquationParameters = new Array(2);
  10706. this._blendConstants = new Array(4);
  10707. this.reset();
  10708. }
  10709. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10710. get: function () {
  10711. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10712. },
  10713. enumerable: true,
  10714. configurable: true
  10715. });
  10716. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10717. get: function () {
  10718. return this._alphaBlend;
  10719. },
  10720. set: function (value) {
  10721. if (this._alphaBlend === value) {
  10722. return;
  10723. }
  10724. this._alphaBlend = value;
  10725. this._isAlphaBlendDirty = true;
  10726. },
  10727. enumerable: true,
  10728. configurable: true
  10729. });
  10730. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10731. if (this._blendConstants[0] === r &&
  10732. this._blendConstants[1] === g &&
  10733. this._blendConstants[2] === b &&
  10734. this._blendConstants[3] === a) {
  10735. return;
  10736. }
  10737. this._blendConstants[0] = r;
  10738. this._blendConstants[1] = g;
  10739. this._blendConstants[2] = b;
  10740. this._blendConstants[3] = a;
  10741. this._isBlendConstantsDirty = true;
  10742. };
  10743. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10744. if (this._blendFunctionParameters[0] === value0 &&
  10745. this._blendFunctionParameters[1] === value1 &&
  10746. this._blendFunctionParameters[2] === value2 &&
  10747. this._blendFunctionParameters[3] === value3) {
  10748. return;
  10749. }
  10750. this._blendFunctionParameters[0] = value0;
  10751. this._blendFunctionParameters[1] = value1;
  10752. this._blendFunctionParameters[2] = value2;
  10753. this._blendFunctionParameters[3] = value3;
  10754. this._isBlendFunctionParametersDirty = true;
  10755. };
  10756. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10757. if (this._blendEquationParameters[0] === rgb &&
  10758. this._blendEquationParameters[1] === alpha) {
  10759. return;
  10760. }
  10761. this._blendEquationParameters[0] = rgb;
  10762. this._blendEquationParameters[1] = alpha;
  10763. this._isBlendEquationParametersDirty = true;
  10764. };
  10765. _AlphaState.prototype.reset = function () {
  10766. this._alphaBlend = false;
  10767. this._blendFunctionParameters[0] = null;
  10768. this._blendFunctionParameters[1] = null;
  10769. this._blendFunctionParameters[2] = null;
  10770. this._blendFunctionParameters[3] = null;
  10771. this._blendEquationParameters[0] = null;
  10772. this._blendEquationParameters[1] = null;
  10773. this._blendConstants[0] = null;
  10774. this._blendConstants[1] = null;
  10775. this._blendConstants[2] = null;
  10776. this._blendConstants[3] = null;
  10777. this._isAlphaBlendDirty = true;
  10778. this._isBlendFunctionParametersDirty = false;
  10779. this._isBlendEquationParametersDirty = false;
  10780. this._isBlendConstantsDirty = false;
  10781. };
  10782. _AlphaState.prototype.apply = function (gl) {
  10783. if (!this.isDirty) {
  10784. return;
  10785. }
  10786. // Alpha blend
  10787. if (this._isAlphaBlendDirty) {
  10788. if (this._alphaBlend) {
  10789. gl.enable(gl.BLEND);
  10790. }
  10791. else {
  10792. gl.disable(gl.BLEND);
  10793. }
  10794. this._isAlphaBlendDirty = false;
  10795. }
  10796. // Alpha function
  10797. if (this._isBlendFunctionParametersDirty) {
  10798. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10799. this._isBlendFunctionParametersDirty = false;
  10800. }
  10801. // Alpha equation
  10802. if (this._isBlendEquationParametersDirty) {
  10803. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10804. this._isBlendEquationParametersDirty = false;
  10805. }
  10806. // Constants
  10807. if (this._isBlendConstantsDirty) {
  10808. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10809. this._isBlendConstantsDirty = false;
  10810. }
  10811. };
  10812. return _AlphaState;
  10813. }());
  10814. BABYLON._AlphaState = _AlphaState;
  10815. })(BABYLON || (BABYLON = {}));
  10816. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10817. var BABYLON;
  10818. (function (BABYLON) {
  10819. /**
  10820. * @hidden
  10821. **/
  10822. var _DepthCullingState = /** @class */ (function () {
  10823. /**
  10824. * Initializes the state.
  10825. */
  10826. function _DepthCullingState() {
  10827. this._isDepthTestDirty = false;
  10828. this._isDepthMaskDirty = false;
  10829. this._isDepthFuncDirty = false;
  10830. this._isCullFaceDirty = false;
  10831. this._isCullDirty = false;
  10832. this._isZOffsetDirty = false;
  10833. this._isFrontFaceDirty = false;
  10834. this.reset();
  10835. }
  10836. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10837. get: function () {
  10838. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10839. },
  10840. enumerable: true,
  10841. configurable: true
  10842. });
  10843. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10844. get: function () {
  10845. return this._zOffset;
  10846. },
  10847. set: function (value) {
  10848. if (this._zOffset === value) {
  10849. return;
  10850. }
  10851. this._zOffset = value;
  10852. this._isZOffsetDirty = true;
  10853. },
  10854. enumerable: true,
  10855. configurable: true
  10856. });
  10857. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10858. get: function () {
  10859. return this._cullFace;
  10860. },
  10861. set: function (value) {
  10862. if (this._cullFace === value) {
  10863. return;
  10864. }
  10865. this._cullFace = value;
  10866. this._isCullFaceDirty = true;
  10867. },
  10868. enumerable: true,
  10869. configurable: true
  10870. });
  10871. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10872. get: function () {
  10873. return this._cull;
  10874. },
  10875. set: function (value) {
  10876. if (this._cull === value) {
  10877. return;
  10878. }
  10879. this._cull = value;
  10880. this._isCullDirty = true;
  10881. },
  10882. enumerable: true,
  10883. configurable: true
  10884. });
  10885. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10886. get: function () {
  10887. return this._depthFunc;
  10888. },
  10889. set: function (value) {
  10890. if (this._depthFunc === value) {
  10891. return;
  10892. }
  10893. this._depthFunc = value;
  10894. this._isDepthFuncDirty = true;
  10895. },
  10896. enumerable: true,
  10897. configurable: true
  10898. });
  10899. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10900. get: function () {
  10901. return this._depthMask;
  10902. },
  10903. set: function (value) {
  10904. if (this._depthMask === value) {
  10905. return;
  10906. }
  10907. this._depthMask = value;
  10908. this._isDepthMaskDirty = true;
  10909. },
  10910. enumerable: true,
  10911. configurable: true
  10912. });
  10913. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10914. get: function () {
  10915. return this._depthTest;
  10916. },
  10917. set: function (value) {
  10918. if (this._depthTest === value) {
  10919. return;
  10920. }
  10921. this._depthTest = value;
  10922. this._isDepthTestDirty = true;
  10923. },
  10924. enumerable: true,
  10925. configurable: true
  10926. });
  10927. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10928. get: function () {
  10929. return this._frontFace;
  10930. },
  10931. set: function (value) {
  10932. if (this._frontFace === value) {
  10933. return;
  10934. }
  10935. this._frontFace = value;
  10936. this._isFrontFaceDirty = true;
  10937. },
  10938. enumerable: true,
  10939. configurable: true
  10940. });
  10941. _DepthCullingState.prototype.reset = function () {
  10942. this._depthMask = true;
  10943. this._depthTest = true;
  10944. this._depthFunc = null;
  10945. this._cullFace = null;
  10946. this._cull = null;
  10947. this._zOffset = 0;
  10948. this._frontFace = null;
  10949. this._isDepthTestDirty = true;
  10950. this._isDepthMaskDirty = true;
  10951. this._isDepthFuncDirty = false;
  10952. this._isCullFaceDirty = false;
  10953. this._isCullDirty = false;
  10954. this._isZOffsetDirty = false;
  10955. this._isFrontFaceDirty = false;
  10956. };
  10957. _DepthCullingState.prototype.apply = function (gl) {
  10958. if (!this.isDirty) {
  10959. return;
  10960. }
  10961. // Cull
  10962. if (this._isCullDirty) {
  10963. if (this.cull) {
  10964. gl.enable(gl.CULL_FACE);
  10965. }
  10966. else {
  10967. gl.disable(gl.CULL_FACE);
  10968. }
  10969. this._isCullDirty = false;
  10970. }
  10971. // Cull face
  10972. if (this._isCullFaceDirty) {
  10973. gl.cullFace(this.cullFace);
  10974. this._isCullFaceDirty = false;
  10975. }
  10976. // Depth mask
  10977. if (this._isDepthMaskDirty) {
  10978. gl.depthMask(this.depthMask);
  10979. this._isDepthMaskDirty = false;
  10980. }
  10981. // Depth test
  10982. if (this._isDepthTestDirty) {
  10983. if (this.depthTest) {
  10984. gl.enable(gl.DEPTH_TEST);
  10985. }
  10986. else {
  10987. gl.disable(gl.DEPTH_TEST);
  10988. }
  10989. this._isDepthTestDirty = false;
  10990. }
  10991. // Depth func
  10992. if (this._isDepthFuncDirty) {
  10993. gl.depthFunc(this.depthFunc);
  10994. this._isDepthFuncDirty = false;
  10995. }
  10996. // zOffset
  10997. if (this._isZOffsetDirty) {
  10998. if (this.zOffset) {
  10999. gl.enable(gl.POLYGON_OFFSET_FILL);
  11000. gl.polygonOffset(this.zOffset, 0);
  11001. }
  11002. else {
  11003. gl.disable(gl.POLYGON_OFFSET_FILL);
  11004. }
  11005. this._isZOffsetDirty = false;
  11006. }
  11007. // Front face
  11008. if (this._isFrontFaceDirty) {
  11009. gl.frontFace(this.frontFace);
  11010. this._isFrontFaceDirty = false;
  11011. }
  11012. };
  11013. return _DepthCullingState;
  11014. }());
  11015. BABYLON._DepthCullingState = _DepthCullingState;
  11016. })(BABYLON || (BABYLON = {}));
  11017. //# sourceMappingURL=babylon.depthCullingState.js.map
  11018. var BABYLON;
  11019. (function (BABYLON) {
  11020. /**
  11021. * @hidden
  11022. **/
  11023. var _StencilState = /** @class */ (function () {
  11024. function _StencilState() {
  11025. this._isStencilTestDirty = false;
  11026. this._isStencilMaskDirty = false;
  11027. this._isStencilFuncDirty = false;
  11028. this._isStencilOpDirty = false;
  11029. this.reset();
  11030. }
  11031. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11032. get: function () {
  11033. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11034. },
  11035. enumerable: true,
  11036. configurable: true
  11037. });
  11038. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11039. get: function () {
  11040. return this._stencilFunc;
  11041. },
  11042. set: function (value) {
  11043. if (this._stencilFunc === value) {
  11044. return;
  11045. }
  11046. this._stencilFunc = value;
  11047. this._isStencilFuncDirty = true;
  11048. },
  11049. enumerable: true,
  11050. configurable: true
  11051. });
  11052. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11053. get: function () {
  11054. return this._stencilFuncRef;
  11055. },
  11056. set: function (value) {
  11057. if (this._stencilFuncRef === value) {
  11058. return;
  11059. }
  11060. this._stencilFuncRef = value;
  11061. this._isStencilFuncDirty = true;
  11062. },
  11063. enumerable: true,
  11064. configurable: true
  11065. });
  11066. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11067. get: function () {
  11068. return this._stencilFuncMask;
  11069. },
  11070. set: function (value) {
  11071. if (this._stencilFuncMask === value) {
  11072. return;
  11073. }
  11074. this._stencilFuncMask = value;
  11075. this._isStencilFuncDirty = true;
  11076. },
  11077. enumerable: true,
  11078. configurable: true
  11079. });
  11080. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11081. get: function () {
  11082. return this._stencilOpStencilFail;
  11083. },
  11084. set: function (value) {
  11085. if (this._stencilOpStencilFail === value) {
  11086. return;
  11087. }
  11088. this._stencilOpStencilFail = value;
  11089. this._isStencilOpDirty = true;
  11090. },
  11091. enumerable: true,
  11092. configurable: true
  11093. });
  11094. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11095. get: function () {
  11096. return this._stencilOpDepthFail;
  11097. },
  11098. set: function (value) {
  11099. if (this._stencilOpDepthFail === value) {
  11100. return;
  11101. }
  11102. this._stencilOpDepthFail = value;
  11103. this._isStencilOpDirty = true;
  11104. },
  11105. enumerable: true,
  11106. configurable: true
  11107. });
  11108. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11109. get: function () {
  11110. return this._stencilOpStencilDepthPass;
  11111. },
  11112. set: function (value) {
  11113. if (this._stencilOpStencilDepthPass === value) {
  11114. return;
  11115. }
  11116. this._stencilOpStencilDepthPass = value;
  11117. this._isStencilOpDirty = true;
  11118. },
  11119. enumerable: true,
  11120. configurable: true
  11121. });
  11122. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11123. get: function () {
  11124. return this._stencilMask;
  11125. },
  11126. set: function (value) {
  11127. if (this._stencilMask === value) {
  11128. return;
  11129. }
  11130. this._stencilMask = value;
  11131. this._isStencilMaskDirty = true;
  11132. },
  11133. enumerable: true,
  11134. configurable: true
  11135. });
  11136. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11137. get: function () {
  11138. return this._stencilTest;
  11139. },
  11140. set: function (value) {
  11141. if (this._stencilTest === value) {
  11142. return;
  11143. }
  11144. this._stencilTest = value;
  11145. this._isStencilTestDirty = true;
  11146. },
  11147. enumerable: true,
  11148. configurable: true
  11149. });
  11150. _StencilState.prototype.reset = function () {
  11151. this._stencilTest = false;
  11152. this._stencilMask = 0xFF;
  11153. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11154. this._stencilFuncRef = 1;
  11155. this._stencilFuncMask = 0xFF;
  11156. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11157. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11158. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11159. this._isStencilTestDirty = true;
  11160. this._isStencilMaskDirty = true;
  11161. this._isStencilFuncDirty = true;
  11162. this._isStencilOpDirty = true;
  11163. };
  11164. _StencilState.prototype.apply = function (gl) {
  11165. if (!this.isDirty) {
  11166. return;
  11167. }
  11168. // Stencil test
  11169. if (this._isStencilTestDirty) {
  11170. if (this.stencilTest) {
  11171. gl.enable(gl.STENCIL_TEST);
  11172. }
  11173. else {
  11174. gl.disable(gl.STENCIL_TEST);
  11175. }
  11176. this._isStencilTestDirty = false;
  11177. }
  11178. // Stencil mask
  11179. if (this._isStencilMaskDirty) {
  11180. gl.stencilMask(this.stencilMask);
  11181. this._isStencilMaskDirty = false;
  11182. }
  11183. // Stencil func
  11184. if (this._isStencilFuncDirty) {
  11185. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11186. this._isStencilFuncDirty = false;
  11187. }
  11188. // Stencil op
  11189. if (this._isStencilOpDirty) {
  11190. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11191. this._isStencilOpDirty = false;
  11192. }
  11193. };
  11194. return _StencilState;
  11195. }());
  11196. BABYLON._StencilState = _StencilState;
  11197. })(BABYLON || (BABYLON = {}));
  11198. //# sourceMappingURL=babylon.stencilState.js.map
  11199. var __assign = (this && this.__assign) || function () {
  11200. __assign = Object.assign || function(t) {
  11201. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11202. s = arguments[i];
  11203. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11204. t[p] = s[p];
  11205. }
  11206. return t;
  11207. };
  11208. return __assign.apply(this, arguments);
  11209. };
  11210. var BABYLON;
  11211. (function (BABYLON) {
  11212. /**
  11213. * Keeps track of all the buffer info used in engine.
  11214. */
  11215. var BufferPointer = /** @class */ (function () {
  11216. function BufferPointer() {
  11217. }
  11218. return BufferPointer;
  11219. }());
  11220. /**
  11221. * Interface for attribute information associated with buffer instanciation
  11222. */
  11223. var InstancingAttributeInfo = /** @class */ (function () {
  11224. function InstancingAttributeInfo() {
  11225. }
  11226. return InstancingAttributeInfo;
  11227. }());
  11228. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11229. /**
  11230. * Define options used to create a render target texture
  11231. */
  11232. var RenderTargetCreationOptions = /** @class */ (function () {
  11233. function RenderTargetCreationOptions() {
  11234. }
  11235. return RenderTargetCreationOptions;
  11236. }());
  11237. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11238. /**
  11239. * Define options used to create a depth texture
  11240. */
  11241. var DepthTextureCreationOptions = /** @class */ (function () {
  11242. function DepthTextureCreationOptions() {
  11243. }
  11244. return DepthTextureCreationOptions;
  11245. }());
  11246. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11247. /**
  11248. * Class used to describe the capabilities of the engine relatively to the current browser
  11249. */
  11250. var EngineCapabilities = /** @class */ (function () {
  11251. function EngineCapabilities() {
  11252. }
  11253. return EngineCapabilities;
  11254. }());
  11255. BABYLON.EngineCapabilities = EngineCapabilities;
  11256. /**
  11257. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11258. */
  11259. var Engine = /** @class */ (function () {
  11260. /**
  11261. * Creates a new engine
  11262. * @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
  11263. * @param antialias defines enable antialiasing (default: false)
  11264. * @param options defines further options to be sent to the getContext() function
  11265. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11266. */
  11267. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11268. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11269. var _this = this;
  11270. // Public members
  11271. /**
  11272. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11273. */
  11274. this.forcePOTTextures = false;
  11275. /**
  11276. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11277. */
  11278. this.isFullscreen = false;
  11279. /**
  11280. * Gets a boolean indicating if the pointer is currently locked
  11281. */
  11282. this.isPointerLock = false;
  11283. /**
  11284. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11285. */
  11286. this.cullBackFaces = true;
  11287. /**
  11288. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11289. */
  11290. this.renderEvenInBackground = true;
  11291. /**
  11292. * Gets or sets a boolean indicating that cache can be kept between frames
  11293. */
  11294. this.preventCacheWipeBetweenFrames = false;
  11295. /**
  11296. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11297. **/
  11298. this.enableOfflineSupport = false;
  11299. /**
  11300. * 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)
  11301. **/
  11302. this.disableManifestCheck = false;
  11303. /**
  11304. * Gets the list of created scenes
  11305. */
  11306. this.scenes = new Array();
  11307. /**
  11308. * Gets the list of created postprocesses
  11309. */
  11310. this.postProcesses = new Array();
  11311. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11312. this.validateShaderPrograms = false;
  11313. // Observables
  11314. /**
  11315. * Observable event triggered each time the rendering canvas is resized
  11316. */
  11317. this.onResizeObservable = new BABYLON.Observable();
  11318. /**
  11319. * Observable event triggered each time the canvas loses focus
  11320. */
  11321. this.onCanvasBlurObservable = new BABYLON.Observable();
  11322. /**
  11323. * Observable event triggered each time the canvas gains focus
  11324. */
  11325. this.onCanvasFocusObservable = new BABYLON.Observable();
  11326. /**
  11327. * Observable event triggered each time the canvas receives pointerout event
  11328. */
  11329. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11330. /**
  11331. * Observable event triggered before each texture is initialized
  11332. */
  11333. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11334. //WebVR
  11335. this._vrDisplay = undefined;
  11336. this._vrSupported = false;
  11337. this._vrExclusivePointerMode = false;
  11338. // Uniform buffers list
  11339. /**
  11340. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11341. */
  11342. this.disableUniformBuffers = false;
  11343. /** @hidden */
  11344. this._uniformBuffers = new Array();
  11345. // Observables
  11346. /**
  11347. * Observable raised when the engine begins a new frame
  11348. */
  11349. this.onBeginFrameObservable = new BABYLON.Observable();
  11350. /**
  11351. * Observable raised when the engine ends the current frame
  11352. */
  11353. this.onEndFrameObservable = new BABYLON.Observable();
  11354. /**
  11355. * Observable raised when the engine is about to compile a shader
  11356. */
  11357. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11358. /**
  11359. * Observable raised when the engine has jsut compiled a shader
  11360. */
  11361. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11362. this._windowIsBackground = false;
  11363. this._webGLVersion = 1.0;
  11364. /** @hidden */
  11365. this._badOS = false;
  11366. /** @hidden */
  11367. this._badDesktopOS = false;
  11368. /**
  11369. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11370. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11371. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11372. */
  11373. this.disableTextureBindingOptimization = false;
  11374. /**
  11375. * Observable signaled when VR display mode changes
  11376. */
  11377. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11378. /**
  11379. * Observable signaled when VR request present is complete
  11380. */
  11381. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11382. /**
  11383. * Observable signaled when VR request present starts
  11384. */
  11385. this.onVRRequestPresentStart = new BABYLON.Observable();
  11386. this._colorWrite = true;
  11387. /** @hidden */
  11388. this._drawCalls = new BABYLON.PerfCounter();
  11389. /** @hidden */
  11390. this._textureCollisions = new BABYLON.PerfCounter();
  11391. this._renderingQueueLaunched = false;
  11392. this._activeRenderLoops = new Array();
  11393. // Deterministic lockstepMaxSteps
  11394. this._deterministicLockstep = false;
  11395. this._lockstepMaxSteps = 4;
  11396. // Lost context
  11397. /**
  11398. * Observable signaled when a context lost event is raised
  11399. */
  11400. this.onContextLostObservable = new BABYLON.Observable();
  11401. /**
  11402. * Observable signaled when a context restored event is raised
  11403. */
  11404. this.onContextRestoredObservable = new BABYLON.Observable();
  11405. this._contextWasLost = false;
  11406. this._doNotHandleContextLost = false;
  11407. // FPS
  11408. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11409. this._fps = 60;
  11410. this._deltaTime = 0;
  11411. /**
  11412. * Turn this value on if you want to pause FPS computation when in background
  11413. */
  11414. this.disablePerformanceMonitorInBackground = false;
  11415. // States
  11416. /** @hidden */
  11417. this._depthCullingState = new BABYLON._DepthCullingState();
  11418. /** @hidden */
  11419. this._stencilState = new BABYLON._StencilState();
  11420. /** @hidden */
  11421. this._alphaState = new BABYLON._AlphaState();
  11422. /** @hidden */
  11423. this._alphaMode = Engine.ALPHA_DISABLE;
  11424. // Cache
  11425. this._internalTexturesCache = new Array();
  11426. /** @hidden */
  11427. this._activeChannel = 0;
  11428. this._currentTextureChannel = -1;
  11429. /** @hidden */
  11430. this._boundTexturesCache = {};
  11431. this._compiledEffects = {};
  11432. this._vertexAttribArraysEnabled = [];
  11433. this._uintIndicesCurrentlySet = false;
  11434. this._currentBoundBuffer = new Array();
  11435. /** @hidden */
  11436. this._currentFramebuffer = null;
  11437. this._currentBufferPointers = new Array();
  11438. this._currentInstanceLocations = new Array();
  11439. this._currentInstanceBuffers = new Array();
  11440. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11441. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11442. this._vaoRecordInProgress = false;
  11443. this._mustWipeVertexAttributes = false;
  11444. this._nextFreeTextureSlots = new Array();
  11445. this._maxSimultaneousTextures = 0;
  11446. this._activeRequests = new Array();
  11447. // Hardware supported Compressed Textures
  11448. this._texturesSupported = new Array();
  11449. /**
  11450. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11451. */
  11452. this.premultipliedAlpha = true;
  11453. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11454. this._onVRFullScreenTriggered = function () {
  11455. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11456. //get the old size before we change
  11457. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11458. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11459. //get the width and height, change the render size
  11460. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11461. _this.setHardwareScalingLevel(1);
  11462. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11463. }
  11464. else {
  11465. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11466. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11467. }
  11468. };
  11469. this._unpackFlipYCached = null;
  11470. this._boundUniforms = {};
  11471. // Register promises
  11472. BABYLON.PromisePolyfill.Apply();
  11473. var canvas = null;
  11474. Engine.Instances.push(this);
  11475. if (!canvasOrContext) {
  11476. return;
  11477. }
  11478. options = options || {};
  11479. if (canvasOrContext.getContext) {
  11480. canvas = canvasOrContext;
  11481. this._renderingCanvas = canvas;
  11482. if (antialias != null) {
  11483. options.antialias = antialias;
  11484. }
  11485. if (options.deterministicLockstep === undefined) {
  11486. options.deterministicLockstep = false;
  11487. }
  11488. if (options.lockstepMaxSteps === undefined) {
  11489. options.lockstepMaxSteps = 4;
  11490. }
  11491. if (options.preserveDrawingBuffer === undefined) {
  11492. options.preserveDrawingBuffer = false;
  11493. }
  11494. if (options.audioEngine === undefined) {
  11495. options.audioEngine = true;
  11496. }
  11497. if (options.stencil === undefined) {
  11498. options.stencil = true;
  11499. }
  11500. if (options.premultipliedAlpha === false) {
  11501. this.premultipliedAlpha = false;
  11502. }
  11503. this._deterministicLockstep = options.deterministicLockstep;
  11504. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11505. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11506. // Exceptions
  11507. if (navigator && navigator.userAgent) {
  11508. var ua = navigator.userAgent;
  11509. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11510. var exception = _a[_i];
  11511. var key = exception.key;
  11512. var targets = exception.targets;
  11513. if (ua.indexOf(key) > -1) {
  11514. if (exception.capture && exception.captureConstraint) {
  11515. var capture = exception.capture;
  11516. var constraint = exception.captureConstraint;
  11517. var regex = new RegExp(capture);
  11518. var matches = regex.exec(ua);
  11519. if (matches && matches.length > 0) {
  11520. var capturedValue = parseInt(matches[matches.length - 1]);
  11521. if (capturedValue >= constraint) {
  11522. continue;
  11523. }
  11524. }
  11525. }
  11526. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11527. var target = targets_1[_b];
  11528. switch (target) {
  11529. case "uniformBuffer":
  11530. this.disableUniformBuffers = true;
  11531. break;
  11532. case "textureBindingOptimization":
  11533. this.disableTextureBindingOptimization = true;
  11534. break;
  11535. }
  11536. }
  11537. }
  11538. }
  11539. }
  11540. // GL
  11541. if (!options.disableWebGL2Support) {
  11542. try {
  11543. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11544. if (this._gl) {
  11545. this._webGLVersion = 2.0;
  11546. }
  11547. }
  11548. catch (e) {
  11549. // Do nothing
  11550. }
  11551. }
  11552. if (!this._gl) {
  11553. if (!canvas) {
  11554. throw new Error("The provided canvas is null or undefined.");
  11555. }
  11556. try {
  11557. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11558. }
  11559. catch (e) {
  11560. throw new Error("WebGL not supported");
  11561. }
  11562. }
  11563. if (!this._gl) {
  11564. throw new Error("WebGL not supported");
  11565. }
  11566. this._onCanvasFocus = function () {
  11567. _this.onCanvasFocusObservable.notifyObservers(_this);
  11568. };
  11569. this._onCanvasBlur = function () {
  11570. _this.onCanvasBlurObservable.notifyObservers(_this);
  11571. };
  11572. canvas.addEventListener("focus", this._onCanvasFocus);
  11573. canvas.addEventListener("blur", this._onCanvasBlur);
  11574. this._onBlur = function () {
  11575. if (_this.disablePerformanceMonitorInBackground) {
  11576. _this._performanceMonitor.disable();
  11577. }
  11578. _this._windowIsBackground = true;
  11579. };
  11580. this._onFocus = function () {
  11581. if (_this.disablePerformanceMonitorInBackground) {
  11582. _this._performanceMonitor.enable();
  11583. }
  11584. _this._windowIsBackground = false;
  11585. };
  11586. this._onCanvasPointerOut = function (ev) {
  11587. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11588. };
  11589. window.addEventListener("blur", this._onBlur);
  11590. window.addEventListener("focus", this._onFocus);
  11591. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11592. // Context lost
  11593. if (!this._doNotHandleContextLost) {
  11594. this._onContextLost = function (evt) {
  11595. evt.preventDefault();
  11596. _this._contextWasLost = true;
  11597. BABYLON.Tools.Warn("WebGL context lost.");
  11598. _this.onContextLostObservable.notifyObservers(_this);
  11599. };
  11600. this._onContextRestored = function (evt) {
  11601. // Adding a timeout to avoid race condition at browser level
  11602. setTimeout(function () {
  11603. // Rebuild gl context
  11604. _this._initGLContext();
  11605. // Rebuild effects
  11606. _this._rebuildEffects();
  11607. // Rebuild textures
  11608. _this._rebuildInternalTextures();
  11609. // Rebuild buffers
  11610. _this._rebuildBuffers();
  11611. // Cache
  11612. _this.wipeCaches(true);
  11613. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11614. _this.onContextRestoredObservable.notifyObservers(_this);
  11615. _this._contextWasLost = false;
  11616. }, 0);
  11617. };
  11618. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11619. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11620. }
  11621. }
  11622. else {
  11623. this._gl = canvasOrContext;
  11624. this._renderingCanvas = this._gl.canvas;
  11625. if (this._gl.renderbufferStorageMultisample) {
  11626. this._webGLVersion = 2.0;
  11627. }
  11628. options.stencil = this._gl.getContextAttributes().stencil;
  11629. }
  11630. // Viewport
  11631. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11632. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11633. this.resize();
  11634. this._isStencilEnable = options.stencil ? true : false;
  11635. this._initGLContext();
  11636. if (canvas) {
  11637. // Fullscreen
  11638. this._onFullscreenChange = function () {
  11639. if (document.fullscreen !== undefined) {
  11640. _this.isFullscreen = document.fullscreen;
  11641. }
  11642. else if (document.mozFullScreen !== undefined) {
  11643. _this.isFullscreen = document.mozFullScreen;
  11644. }
  11645. else if (document.webkitIsFullScreen !== undefined) {
  11646. _this.isFullscreen = document.webkitIsFullScreen;
  11647. }
  11648. else if (document.msIsFullScreen !== undefined) {
  11649. _this.isFullscreen = document.msIsFullScreen;
  11650. }
  11651. // Pointer lock
  11652. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11653. canvas.requestPointerLock = canvas.requestPointerLock ||
  11654. canvas.msRequestPointerLock ||
  11655. canvas.mozRequestPointerLock ||
  11656. canvas.webkitRequestPointerLock;
  11657. if (canvas.requestPointerLock) {
  11658. canvas.requestPointerLock();
  11659. }
  11660. }
  11661. };
  11662. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11663. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11664. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11665. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11666. // Pointer lock
  11667. this._onPointerLockChange = function () {
  11668. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11669. document.webkitPointerLockElement === canvas ||
  11670. document.msPointerLockElement === canvas ||
  11671. document.pointerLockElement === canvas);
  11672. };
  11673. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11674. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11675. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11676. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11677. this._onVRDisplayPointerRestricted = function () {
  11678. if (canvas) {
  11679. canvas.requestPointerLock();
  11680. }
  11681. };
  11682. this._onVRDisplayPointerUnrestricted = function () {
  11683. document.exitPointerLock();
  11684. };
  11685. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11686. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11687. }
  11688. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11689. Engine.audioEngine = new BABYLON.AudioEngine();
  11690. }
  11691. // Prepare buffer pointers
  11692. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11693. this._currentBufferPointers[i] = new BufferPointer();
  11694. }
  11695. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11696. // Load WebVR Devices
  11697. if (options.autoEnableWebVR) {
  11698. this.initWebVR();
  11699. }
  11700. // Detect if we are running on a faulty buggy OS.
  11701. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11702. // Detect if we are running on a faulty buggy desktop OS.
  11703. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11704. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11705. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11706. }
  11707. Object.defineProperty(Engine, "LastCreatedEngine", {
  11708. /**
  11709. * Gets the latest created engine
  11710. */
  11711. get: function () {
  11712. if (Engine.Instances.length === 0) {
  11713. return null;
  11714. }
  11715. return Engine.Instances[Engine.Instances.length - 1];
  11716. },
  11717. enumerable: true,
  11718. configurable: true
  11719. });
  11720. Object.defineProperty(Engine, "LastCreatedScene", {
  11721. /**
  11722. * Gets the latest created scene
  11723. */
  11724. get: function () {
  11725. var lastCreatedEngine = Engine.LastCreatedEngine;
  11726. if (!lastCreatedEngine) {
  11727. return null;
  11728. }
  11729. if (lastCreatedEngine.scenes.length === 0) {
  11730. return null;
  11731. }
  11732. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11733. },
  11734. enumerable: true,
  11735. configurable: true
  11736. });
  11737. /**
  11738. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11739. * @param flag defines which part of the materials must be marked as dirty
  11740. * @param predicate defines a predicate used to filter which materials should be affected
  11741. */
  11742. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11743. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11744. var engine = Engine.Instances[engineIndex];
  11745. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11746. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11747. }
  11748. }
  11749. };
  11750. Object.defineProperty(Engine, "Version", {
  11751. /**
  11752. * Returns the current version of the framework
  11753. */
  11754. get: function () {
  11755. return "3.3.0-beta.4";
  11756. },
  11757. enumerable: true,
  11758. configurable: true
  11759. });
  11760. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11761. /**
  11762. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11763. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11764. */
  11765. get: function () {
  11766. return this._vrExclusivePointerMode;
  11767. },
  11768. enumerable: true,
  11769. configurable: true
  11770. });
  11771. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11772. /**
  11773. * Gets a boolean indicating that the engine supports uniform buffers
  11774. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11775. */
  11776. get: function () {
  11777. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11778. },
  11779. enumerable: true,
  11780. configurable: true
  11781. });
  11782. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11783. /**
  11784. * Gets a boolean indicating that only power of 2 textures are supported
  11785. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11786. */
  11787. get: function () {
  11788. return this._webGLVersion < 2 || this.forcePOTTextures;
  11789. },
  11790. enumerable: true,
  11791. configurable: true
  11792. });
  11793. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11794. /**
  11795. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11796. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11797. */
  11798. get: function () {
  11799. return this._doNotHandleContextLost;
  11800. },
  11801. set: function (value) {
  11802. this._doNotHandleContextLost = value;
  11803. },
  11804. enumerable: true,
  11805. configurable: true
  11806. });
  11807. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11808. /**
  11809. * Gets the performance monitor attached to this engine
  11810. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11811. */
  11812. get: function () {
  11813. return this._performanceMonitor;
  11814. },
  11815. enumerable: true,
  11816. configurable: true
  11817. });
  11818. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11819. /**
  11820. * Gets the list of texture formats supported
  11821. */
  11822. get: function () {
  11823. return this._texturesSupported;
  11824. },
  11825. enumerable: true,
  11826. configurable: true
  11827. });
  11828. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11829. /**
  11830. * Gets the list of texture formats in use
  11831. */
  11832. get: function () {
  11833. return this._textureFormatInUse;
  11834. },
  11835. enumerable: true,
  11836. configurable: true
  11837. });
  11838. Object.defineProperty(Engine.prototype, "currentViewport", {
  11839. /**
  11840. * Gets the current viewport
  11841. */
  11842. get: function () {
  11843. return this._cachedViewport;
  11844. },
  11845. enumerable: true,
  11846. configurable: true
  11847. });
  11848. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11849. /**
  11850. * Gets the default empty texture
  11851. */
  11852. get: function () {
  11853. if (!this._emptyTexture) {
  11854. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11855. }
  11856. return this._emptyTexture;
  11857. },
  11858. enumerable: true,
  11859. configurable: true
  11860. });
  11861. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11862. /**
  11863. * Gets the default empty 3D texture
  11864. */
  11865. get: function () {
  11866. if (!this._emptyTexture3D) {
  11867. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11868. }
  11869. return this._emptyTexture3D;
  11870. },
  11871. enumerable: true,
  11872. configurable: true
  11873. });
  11874. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11875. /**
  11876. * Gets the default empty cube texture
  11877. */
  11878. get: function () {
  11879. if (!this._emptyCubeTexture) {
  11880. var faceData = new Uint8Array(4);
  11881. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11882. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11883. }
  11884. return this._emptyCubeTexture;
  11885. },
  11886. enumerable: true,
  11887. configurable: true
  11888. });
  11889. Engine.prototype._rebuildInternalTextures = function () {
  11890. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11891. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11892. var internalTexture = currentState_1[_i];
  11893. internalTexture._rebuild();
  11894. }
  11895. };
  11896. Engine.prototype._rebuildEffects = function () {
  11897. for (var key in this._compiledEffects) {
  11898. var effect = this._compiledEffects[key];
  11899. effect._prepareEffect();
  11900. }
  11901. BABYLON.Effect.ResetCache();
  11902. };
  11903. Engine.prototype._rebuildBuffers = function () {
  11904. // Index / Vertex
  11905. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11906. var scene = _a[_i];
  11907. scene.resetCachedMaterial();
  11908. scene._rebuildGeometries();
  11909. scene._rebuildTextures();
  11910. }
  11911. // Uniforms
  11912. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11913. var uniformBuffer = _c[_b];
  11914. uniformBuffer._rebuild();
  11915. }
  11916. };
  11917. Engine.prototype._initGLContext = function () {
  11918. // Caps
  11919. this._caps = new EngineCapabilities();
  11920. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11921. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11922. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11923. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11924. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11925. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11926. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11927. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11928. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11929. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11930. // Infos
  11931. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11932. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11933. if (rendererInfo != null) {
  11934. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11935. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11936. }
  11937. if (!this._glVendor) {
  11938. this._glVendor = "Unknown vendor";
  11939. }
  11940. if (!this._glRenderer) {
  11941. this._glRenderer = "Unknown renderer";
  11942. }
  11943. // Constants
  11944. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11945. if (this._gl.RGBA16F !== 0x881A) {
  11946. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11947. }
  11948. if (this._gl.RGBA32F !== 0x8814) {
  11949. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11950. }
  11951. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11952. this._gl.DEPTH24_STENCIL8 = 35056;
  11953. }
  11954. // Extensions
  11955. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11956. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11957. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11958. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11959. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11960. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11961. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11962. 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');
  11963. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11964. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11965. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11966. this._caps.highPrecisionShaderSupported = true;
  11967. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11968. if (this._caps.timerQuery) {
  11969. if (this._webGLVersion === 1) {
  11970. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11971. }
  11972. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11973. }
  11974. // Checks if some of the format renders first to allow the use of webgl inspector.
  11975. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11976. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11977. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11978. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11979. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11980. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11981. if (this._webGLVersion > 1) {
  11982. this._gl.HALF_FLOAT_OES = 0x140B;
  11983. }
  11984. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11985. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11986. // Draw buffers
  11987. if (this._webGLVersion > 1) {
  11988. this._caps.drawBuffersExtension = true;
  11989. }
  11990. else {
  11991. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11992. if (drawBuffersExtension !== null) {
  11993. this._caps.drawBuffersExtension = true;
  11994. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11995. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11996. for (var i = 0; i < 16; i++) {
  11997. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11998. }
  11999. }
  12000. else {
  12001. this._caps.drawBuffersExtension = false;
  12002. }
  12003. }
  12004. // Depth Texture
  12005. if (this._webGLVersion > 1) {
  12006. this._caps.depthTextureExtension = true;
  12007. }
  12008. else {
  12009. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12010. if (depthTextureExtension != null) {
  12011. this._caps.depthTextureExtension = true;
  12012. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12013. }
  12014. }
  12015. // Vertex array object
  12016. if (this._webGLVersion > 1) {
  12017. this._caps.vertexArrayObject = true;
  12018. }
  12019. else {
  12020. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12021. if (vertexArrayObjectExtension != null) {
  12022. this._caps.vertexArrayObject = true;
  12023. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12024. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12025. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12026. }
  12027. else {
  12028. this._caps.vertexArrayObject = false;
  12029. }
  12030. }
  12031. // Instances count
  12032. if (this._webGLVersion > 1) {
  12033. this._caps.instancedArrays = true;
  12034. }
  12035. else {
  12036. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12037. if (instanceExtension != null) {
  12038. this._caps.instancedArrays = true;
  12039. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12040. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12041. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12042. }
  12043. else {
  12044. this._caps.instancedArrays = false;
  12045. }
  12046. }
  12047. // Intelligently add supported compressed formats in order to check for.
  12048. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12049. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12050. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12051. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12052. if (this._caps.astc)
  12053. this.texturesSupported.push('-astc.ktx');
  12054. if (this._caps.s3tc)
  12055. this.texturesSupported.push('-dxt.ktx');
  12056. if (this._caps.pvrtc)
  12057. this.texturesSupported.push('-pvrtc.ktx');
  12058. if (this._caps.etc2)
  12059. this.texturesSupported.push('-etc2.ktx');
  12060. if (this._caps.etc1)
  12061. this.texturesSupported.push('-etc1.ktx');
  12062. if (this._gl.getShaderPrecisionFormat) {
  12063. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12064. if (highp) {
  12065. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12066. }
  12067. }
  12068. // Depth buffer
  12069. this.setDepthBuffer(true);
  12070. this.setDepthFunctionToLessOrEqual();
  12071. this.setDepthWrite(true);
  12072. // Texture maps
  12073. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12074. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12075. this._nextFreeTextureSlots.push(slot);
  12076. }
  12077. };
  12078. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12079. /**
  12080. * Gets version of the current webGL context
  12081. */
  12082. get: function () {
  12083. return this._webGLVersion;
  12084. },
  12085. enumerable: true,
  12086. configurable: true
  12087. });
  12088. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12089. /**
  12090. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12091. */
  12092. get: function () {
  12093. return this._isStencilEnable;
  12094. },
  12095. enumerable: true,
  12096. configurable: true
  12097. });
  12098. Engine.prototype._prepareWorkingCanvas = function () {
  12099. if (this._workingCanvas) {
  12100. return;
  12101. }
  12102. this._workingCanvas = document.createElement("canvas");
  12103. var context = this._workingCanvas.getContext("2d");
  12104. if (context) {
  12105. this._workingContext = context;
  12106. }
  12107. };
  12108. /**
  12109. * Reset the texture cache to empty state
  12110. */
  12111. Engine.prototype.resetTextureCache = function () {
  12112. for (var key in this._boundTexturesCache) {
  12113. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12114. continue;
  12115. }
  12116. var boundTexture = this._boundTexturesCache[key];
  12117. if (boundTexture) {
  12118. this._removeDesignatedSlot(boundTexture);
  12119. }
  12120. this._boundTexturesCache[key] = null;
  12121. }
  12122. if (!this.disableTextureBindingOptimization) {
  12123. this._nextFreeTextureSlots = [];
  12124. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12125. this._nextFreeTextureSlots.push(slot);
  12126. }
  12127. }
  12128. this._currentTextureChannel = -1;
  12129. };
  12130. /**
  12131. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12132. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12133. * @returns true if engine is in deterministic lock step mode
  12134. */
  12135. Engine.prototype.isDeterministicLockStep = function () {
  12136. return this._deterministicLockstep;
  12137. };
  12138. /**
  12139. * Gets the max steps when engine is running in deterministic lock step
  12140. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12141. * @returns the max steps
  12142. */
  12143. Engine.prototype.getLockstepMaxSteps = function () {
  12144. return this._lockstepMaxSteps;
  12145. };
  12146. /**
  12147. * Gets an object containing information about the current webGL context
  12148. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12149. */
  12150. Engine.prototype.getGlInfo = function () {
  12151. return {
  12152. vendor: this._glVendor,
  12153. renderer: this._glRenderer,
  12154. version: this._glVersion
  12155. };
  12156. };
  12157. /**
  12158. * Gets current aspect ratio
  12159. * @param camera defines the camera to use to get the aspect ratio
  12160. * @param useScreen defines if screen size must be used (or the current render target if any)
  12161. * @returns a number defining the aspect ratio
  12162. */
  12163. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12164. if (useScreen === void 0) { useScreen = false; }
  12165. var viewport = camera.viewport;
  12166. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12167. };
  12168. /**
  12169. * Gets current screen aspect ratio
  12170. * @returns a number defining the aspect ratio
  12171. */
  12172. Engine.prototype.getScreenAspectRatio = function () {
  12173. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12174. };
  12175. /**
  12176. * Gets the current render width
  12177. * @param useScreen defines if screen size must be used (or the current render target if any)
  12178. * @returns a number defining the current render width
  12179. */
  12180. Engine.prototype.getRenderWidth = function (useScreen) {
  12181. if (useScreen === void 0) { useScreen = false; }
  12182. if (!useScreen && this._currentRenderTarget) {
  12183. return this._currentRenderTarget.width;
  12184. }
  12185. return this._gl.drawingBufferWidth;
  12186. };
  12187. /**
  12188. * Gets the current render height
  12189. * @param useScreen defines if screen size must be used (or the current render target if any)
  12190. * @returns a number defining the current render height
  12191. */
  12192. Engine.prototype.getRenderHeight = function (useScreen) {
  12193. if (useScreen === void 0) { useScreen = false; }
  12194. if (!useScreen && this._currentRenderTarget) {
  12195. return this._currentRenderTarget.height;
  12196. }
  12197. return this._gl.drawingBufferHeight;
  12198. };
  12199. /**
  12200. * Gets the HTML canvas attached with the current webGL context
  12201. * @returns a HTML canvas
  12202. */
  12203. Engine.prototype.getRenderingCanvas = function () {
  12204. return this._renderingCanvas;
  12205. };
  12206. /**
  12207. * Gets the client rect of the HTML canvas attached with the current webGL context
  12208. * @returns a client rectanglee
  12209. */
  12210. Engine.prototype.getRenderingCanvasClientRect = function () {
  12211. if (!this._renderingCanvas) {
  12212. return null;
  12213. }
  12214. return this._renderingCanvas.getBoundingClientRect();
  12215. };
  12216. /**
  12217. * Defines the hardware scaling level.
  12218. * By default the hardware scaling level is computed from the window device ratio.
  12219. * 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.
  12220. * @param level defines the level to use
  12221. */
  12222. Engine.prototype.setHardwareScalingLevel = function (level) {
  12223. this._hardwareScalingLevel = level;
  12224. this.resize();
  12225. };
  12226. /**
  12227. * Gets the current hardware scaling level.
  12228. * By default the hardware scaling level is computed from the window device ratio.
  12229. * 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.
  12230. * @returns a number indicating the current hardware scaling level
  12231. */
  12232. Engine.prototype.getHardwareScalingLevel = function () {
  12233. return this._hardwareScalingLevel;
  12234. };
  12235. /**
  12236. * Gets the list of loaded textures
  12237. * @returns an array containing all loaded textures
  12238. */
  12239. Engine.prototype.getLoadedTexturesCache = function () {
  12240. return this._internalTexturesCache;
  12241. };
  12242. /**
  12243. * Gets the object containing all engine capabilities
  12244. * @returns the EngineCapabilities object
  12245. */
  12246. Engine.prototype.getCaps = function () {
  12247. return this._caps;
  12248. };
  12249. Object.defineProperty(Engine.prototype, "drawCalls", {
  12250. /** @hidden */
  12251. get: function () {
  12252. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12253. return 0;
  12254. },
  12255. enumerable: true,
  12256. configurable: true
  12257. });
  12258. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12259. /** @hidden */
  12260. get: function () {
  12261. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12262. return null;
  12263. },
  12264. enumerable: true,
  12265. configurable: true
  12266. });
  12267. /**
  12268. * Gets the current depth function
  12269. * @returns a number defining the depth function
  12270. */
  12271. Engine.prototype.getDepthFunction = function () {
  12272. return this._depthCullingState.depthFunc;
  12273. };
  12274. /**
  12275. * Sets the current depth function
  12276. * @param depthFunc defines the function to use
  12277. */
  12278. Engine.prototype.setDepthFunction = function (depthFunc) {
  12279. this._depthCullingState.depthFunc = depthFunc;
  12280. };
  12281. /**
  12282. * Sets the current depth function to GREATER
  12283. */
  12284. Engine.prototype.setDepthFunctionToGreater = function () {
  12285. this._depthCullingState.depthFunc = this._gl.GREATER;
  12286. };
  12287. /**
  12288. * Sets the current depth function to GEQUAL
  12289. */
  12290. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12291. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12292. };
  12293. /**
  12294. * Sets the current depth function to LESS
  12295. */
  12296. Engine.prototype.setDepthFunctionToLess = function () {
  12297. this._depthCullingState.depthFunc = this._gl.LESS;
  12298. };
  12299. /**
  12300. * Sets the current depth function to LEQUAL
  12301. */
  12302. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12303. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12304. };
  12305. /**
  12306. * Gets a boolean indicating if stencil buffer is enabled
  12307. * @returns the current stencil buffer state
  12308. */
  12309. Engine.prototype.getStencilBuffer = function () {
  12310. return this._stencilState.stencilTest;
  12311. };
  12312. /**
  12313. * Enable or disable the stencil buffer
  12314. * @param enable defines if the stencil buffer must be enabled or disabled
  12315. */
  12316. Engine.prototype.setStencilBuffer = function (enable) {
  12317. this._stencilState.stencilTest = enable;
  12318. };
  12319. /**
  12320. * Gets the current stencil mask
  12321. * @returns a number defining the new stencil mask to use
  12322. */
  12323. Engine.prototype.getStencilMask = function () {
  12324. return this._stencilState.stencilMask;
  12325. };
  12326. /**
  12327. * Sets the current stencil mask
  12328. * @param mask defines the new stencil mask to use
  12329. */
  12330. Engine.prototype.setStencilMask = function (mask) {
  12331. this._stencilState.stencilMask = mask;
  12332. };
  12333. /**
  12334. * Gets the current stencil function
  12335. * @returns a number defining the stencil function to use
  12336. */
  12337. Engine.prototype.getStencilFunction = function () {
  12338. return this._stencilState.stencilFunc;
  12339. };
  12340. /**
  12341. * Gets the current stencil reference value
  12342. * @returns a number defining the stencil reference value to use
  12343. */
  12344. Engine.prototype.getStencilFunctionReference = function () {
  12345. return this._stencilState.stencilFuncRef;
  12346. };
  12347. /**
  12348. * Gets the current stencil mask
  12349. * @returns a number defining the stencil mask to use
  12350. */
  12351. Engine.prototype.getStencilFunctionMask = function () {
  12352. return this._stencilState.stencilFuncMask;
  12353. };
  12354. /**
  12355. * Sets the current stencil function
  12356. * @param stencilFunc defines the new stencil function to use
  12357. */
  12358. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12359. this._stencilState.stencilFunc = stencilFunc;
  12360. };
  12361. /**
  12362. * Sets the current stencil reference
  12363. * @param reference defines the new stencil reference to use
  12364. */
  12365. Engine.prototype.setStencilFunctionReference = function (reference) {
  12366. this._stencilState.stencilFuncRef = reference;
  12367. };
  12368. /**
  12369. * Sets the current stencil mask
  12370. * @param mask defines the new stencil mask to use
  12371. */
  12372. Engine.prototype.setStencilFunctionMask = function (mask) {
  12373. this._stencilState.stencilFuncMask = mask;
  12374. };
  12375. /**
  12376. * Gets the current stencil operation when stencil fails
  12377. * @returns a number defining stencil operation to use when stencil fails
  12378. */
  12379. Engine.prototype.getStencilOperationFail = function () {
  12380. return this._stencilState.stencilOpStencilFail;
  12381. };
  12382. /**
  12383. * Gets the current stencil operation when depth fails
  12384. * @returns a number defining stencil operation to use when depth fails
  12385. */
  12386. Engine.prototype.getStencilOperationDepthFail = function () {
  12387. return this._stencilState.stencilOpDepthFail;
  12388. };
  12389. /**
  12390. * Gets the current stencil operation when stencil passes
  12391. * @returns a number defining stencil operation to use when stencil passes
  12392. */
  12393. Engine.prototype.getStencilOperationPass = function () {
  12394. return this._stencilState.stencilOpStencilDepthPass;
  12395. };
  12396. /**
  12397. * Sets the stencil operation to use when stencil fails
  12398. * @param operation defines the stencil operation to use when stencil fails
  12399. */
  12400. Engine.prototype.setStencilOperationFail = function (operation) {
  12401. this._stencilState.stencilOpStencilFail = operation;
  12402. };
  12403. /**
  12404. * Sets the stencil operation to use when depth fails
  12405. * @param operation defines the stencil operation to use when depth fails
  12406. */
  12407. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12408. this._stencilState.stencilOpDepthFail = operation;
  12409. };
  12410. /**
  12411. * Sets the stencil operation to use when stencil passes
  12412. * @param operation defines the stencil operation to use when stencil passes
  12413. */
  12414. Engine.prototype.setStencilOperationPass = function (operation) {
  12415. this._stencilState.stencilOpStencilDepthPass = operation;
  12416. };
  12417. /**
  12418. * Sets a boolean indicating if the dithering state is enabled or disabled
  12419. * @param value defines the dithering state
  12420. */
  12421. Engine.prototype.setDitheringState = function (value) {
  12422. if (value) {
  12423. this._gl.enable(this._gl.DITHER);
  12424. }
  12425. else {
  12426. this._gl.disable(this._gl.DITHER);
  12427. }
  12428. };
  12429. /**
  12430. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12431. * @param value defines the rasterizer state
  12432. */
  12433. Engine.prototype.setRasterizerState = function (value) {
  12434. if (value) {
  12435. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12436. }
  12437. else {
  12438. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12439. }
  12440. };
  12441. /**
  12442. * stop executing a render loop function and remove it from the execution array
  12443. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12444. */
  12445. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12446. if (!renderFunction) {
  12447. this._activeRenderLoops = [];
  12448. return;
  12449. }
  12450. var index = this._activeRenderLoops.indexOf(renderFunction);
  12451. if (index >= 0) {
  12452. this._activeRenderLoops.splice(index, 1);
  12453. }
  12454. };
  12455. /** @hidden */
  12456. Engine.prototype._renderLoop = function () {
  12457. if (!this._contextWasLost) {
  12458. var shouldRender = true;
  12459. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12460. shouldRender = false;
  12461. }
  12462. if (shouldRender) {
  12463. // Start new frame
  12464. this.beginFrame();
  12465. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12466. var renderFunction = this._activeRenderLoops[index];
  12467. renderFunction();
  12468. }
  12469. // Present
  12470. this.endFrame();
  12471. }
  12472. }
  12473. if (this._activeRenderLoops.length > 0) {
  12474. // Register new frame
  12475. var requester = null;
  12476. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12477. requester = this._vrDisplay;
  12478. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12479. }
  12480. else {
  12481. this._renderingQueueLaunched = false;
  12482. }
  12483. };
  12484. /**
  12485. * Register and execute a render loop. The engine can have more than one render function
  12486. * @param renderFunction defines the function to continuously execute
  12487. */
  12488. Engine.prototype.runRenderLoop = function (renderFunction) {
  12489. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12490. return;
  12491. }
  12492. this._activeRenderLoops.push(renderFunction);
  12493. if (!this._renderingQueueLaunched) {
  12494. this._renderingQueueLaunched = true;
  12495. this._bindedRenderFunction = this._renderLoop.bind(this);
  12496. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12497. }
  12498. };
  12499. /**
  12500. * Toggle full screen mode
  12501. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12502. * @param options defines an option object to be sent to the requestFullscreen function
  12503. */
  12504. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12505. if (this.isFullscreen) {
  12506. BABYLON.Tools.ExitFullscreen();
  12507. }
  12508. else {
  12509. this._pointerLockRequested = requestPointerLock;
  12510. if (this._renderingCanvas) {
  12511. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12512. }
  12513. }
  12514. };
  12515. /**
  12516. * Clear the current render buffer or the current render target (if any is set up)
  12517. * @param color defines the color to use
  12518. * @param backBuffer defines if the back buffer must be cleared
  12519. * @param depth defines if the depth buffer must be cleared
  12520. * @param stencil defines if the stencil buffer must be cleared
  12521. */
  12522. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12523. if (stencil === void 0) { stencil = false; }
  12524. this.applyStates();
  12525. var mode = 0;
  12526. if (backBuffer && color) {
  12527. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12528. mode |= this._gl.COLOR_BUFFER_BIT;
  12529. }
  12530. if (depth) {
  12531. this._gl.clearDepth(1.0);
  12532. mode |= this._gl.DEPTH_BUFFER_BIT;
  12533. }
  12534. if (stencil) {
  12535. this._gl.clearStencil(0);
  12536. mode |= this._gl.STENCIL_BUFFER_BIT;
  12537. }
  12538. this._gl.clear(mode);
  12539. };
  12540. /**
  12541. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12542. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12543. * @param y defines the y-coordinate of the corner of the clear rectangle
  12544. * @param width defines the width of the clear rectangle
  12545. * @param height defines the height of the clear rectangle
  12546. * @param clearColor defines the clear color
  12547. */
  12548. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12549. var gl = this._gl;
  12550. // Save state
  12551. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12552. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12553. // Change state
  12554. gl.enable(gl.SCISSOR_TEST);
  12555. gl.scissor(x, y, width, height);
  12556. // Clear
  12557. this.clear(clearColor, true, true, true);
  12558. // Restore state
  12559. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12560. if (curScissor === true) {
  12561. gl.enable(gl.SCISSOR_TEST);
  12562. }
  12563. else {
  12564. gl.disable(gl.SCISSOR_TEST);
  12565. }
  12566. };
  12567. /** @hidden */
  12568. Engine.prototype._viewport = function (x, y, width, height) {
  12569. if (x !== this._viewportCached.x ||
  12570. y !== this._viewportCached.y ||
  12571. width !== this._viewportCached.z ||
  12572. height !== this._viewportCached.w) {
  12573. this._viewportCached.x = x;
  12574. this._viewportCached.y = y;
  12575. this._viewportCached.z = width;
  12576. this._viewportCached.w = height;
  12577. this._gl.viewport(x, y, width, height);
  12578. }
  12579. };
  12580. /**
  12581. * Set the WebGL's viewport
  12582. * @param viewport defines the viewport element to be used
  12583. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12584. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12585. */
  12586. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12587. var width = requiredWidth || this.getRenderWidth();
  12588. var height = requiredHeight || this.getRenderHeight();
  12589. var x = viewport.x || 0;
  12590. var y = viewport.y || 0;
  12591. this._cachedViewport = viewport;
  12592. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12593. };
  12594. /**
  12595. * Directly set the WebGL Viewport
  12596. * @param x defines the x coordinate of the viewport (in screen space)
  12597. * @param y defines the y coordinate of the viewport (in screen space)
  12598. * @param width defines the width of the viewport (in screen space)
  12599. * @param height defines the height of the viewport (in screen space)
  12600. * @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
  12601. */
  12602. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12603. var currentViewport = this._cachedViewport;
  12604. this._cachedViewport = null;
  12605. this._viewport(x, y, width, height);
  12606. return currentViewport;
  12607. };
  12608. /**
  12609. * Begin a new frame
  12610. */
  12611. Engine.prototype.beginFrame = function () {
  12612. this.onBeginFrameObservable.notifyObservers(this);
  12613. this._measureFps();
  12614. };
  12615. /**
  12616. * Enf the current frame
  12617. */
  12618. Engine.prototype.endFrame = function () {
  12619. // Force a flush in case we are using a bad OS.
  12620. if (this._badOS) {
  12621. this.flushFramebuffer();
  12622. }
  12623. // Submit frame to the vr device, if enabled
  12624. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12625. // TODO: We should only submit the frame if we read frameData successfully.
  12626. this._vrDisplay.submitFrame();
  12627. }
  12628. this.onEndFrameObservable.notifyObservers(this);
  12629. };
  12630. /**
  12631. * Resize the view according to the canvas' size
  12632. */
  12633. Engine.prototype.resize = function () {
  12634. // We're not resizing the size of the canvas while in VR mode & presenting
  12635. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12636. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12637. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12638. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12639. }
  12640. };
  12641. /**
  12642. * Force a specific size of the canvas
  12643. * @param width defines the new canvas' width
  12644. * @param height defines the new canvas' height
  12645. */
  12646. Engine.prototype.setSize = function (width, height) {
  12647. if (!this._renderingCanvas) {
  12648. return;
  12649. }
  12650. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12651. return;
  12652. }
  12653. this._renderingCanvas.width = width;
  12654. this._renderingCanvas.height = height;
  12655. for (var index = 0; index < this.scenes.length; index++) {
  12656. var scene = this.scenes[index];
  12657. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12658. var cam = scene.cameras[camIndex];
  12659. cam._currentRenderId = 0;
  12660. }
  12661. }
  12662. if (this.onResizeObservable.hasObservers) {
  12663. this.onResizeObservable.notifyObservers(this);
  12664. }
  12665. };
  12666. // WebVR functions
  12667. /**
  12668. * Gets a boolean indicating if a webVR device was detected
  12669. * @returns true if a webVR device was detected
  12670. */
  12671. Engine.prototype.isVRDevicePresent = function () {
  12672. return !!this._vrDisplay;
  12673. };
  12674. /**
  12675. * Gets the current webVR device
  12676. * @returns the current webVR device (or null)
  12677. */
  12678. Engine.prototype.getVRDevice = function () {
  12679. return this._vrDisplay;
  12680. };
  12681. /**
  12682. * Initializes a webVR display and starts listening to display change events
  12683. * The onVRDisplayChangedObservable will be notified upon these changes
  12684. * @returns The onVRDisplayChangedObservable
  12685. */
  12686. Engine.prototype.initWebVR = function () {
  12687. this.initWebVRAsync();
  12688. return this.onVRDisplayChangedObservable;
  12689. };
  12690. /**
  12691. * Initializes a webVR display and starts listening to display change events
  12692. * The onVRDisplayChangedObservable will be notified upon these changes
  12693. * @returns A promise containing a VRDisplay and if vr is supported
  12694. */
  12695. Engine.prototype.initWebVRAsync = function () {
  12696. var _this = this;
  12697. var notifyObservers = function () {
  12698. var eventArgs = {
  12699. vrDisplay: _this._vrDisplay,
  12700. vrSupported: _this._vrSupported
  12701. };
  12702. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12703. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12704. };
  12705. if (!this._onVrDisplayConnect) {
  12706. this._onVrDisplayConnect = function (event) {
  12707. _this._vrDisplay = event.display;
  12708. notifyObservers();
  12709. };
  12710. this._onVrDisplayDisconnect = function () {
  12711. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12712. _this._vrDisplay = undefined;
  12713. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12714. notifyObservers();
  12715. };
  12716. this._onVrDisplayPresentChange = function () {
  12717. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12718. };
  12719. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12720. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12721. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12722. }
  12723. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12724. this._webVRInitPromise.then(notifyObservers);
  12725. return this._webVRInitPromise;
  12726. };
  12727. /**
  12728. * Call this function to switch to webVR mode
  12729. * Will do nothing if webVR is not supported or if there is no webVR device
  12730. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12731. */
  12732. Engine.prototype.enableVR = function () {
  12733. var _this = this;
  12734. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12735. var onResolved = function () {
  12736. _this.onVRRequestPresentComplete.notifyObservers(true);
  12737. _this._onVRFullScreenTriggered();
  12738. };
  12739. var onRejected = function () {
  12740. _this.onVRRequestPresentComplete.notifyObservers(false);
  12741. };
  12742. this.onVRRequestPresentStart.notifyObservers(this);
  12743. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12744. }
  12745. };
  12746. /**
  12747. * Call this function to leave webVR mode
  12748. * Will do nothing if webVR is not supported or if there is no webVR device
  12749. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12750. */
  12751. Engine.prototype.disableVR = function () {
  12752. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12753. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12754. }
  12755. };
  12756. Engine.prototype._getVRDisplaysAsync = function () {
  12757. var _this = this;
  12758. return new Promise(function (res, rej) {
  12759. if (navigator.getVRDisplays) {
  12760. navigator.getVRDisplays().then(function (devices) {
  12761. _this._vrSupported = true;
  12762. // note that devices may actually be an empty array. This is fine;
  12763. // we expect this._vrDisplay to be undefined in this case.
  12764. _this._vrDisplay = devices[0];
  12765. res({
  12766. vrDisplay: _this._vrDisplay,
  12767. vrSupported: _this._vrSupported
  12768. });
  12769. });
  12770. }
  12771. else {
  12772. _this._vrDisplay = undefined;
  12773. _this._vrSupported = false;
  12774. res({
  12775. vrDisplay: _this._vrDisplay,
  12776. vrSupported: _this._vrSupported
  12777. });
  12778. }
  12779. });
  12780. };
  12781. /**
  12782. * Binds the frame buffer to the specified texture.
  12783. * @param texture The texture to render to or null for the default canvas
  12784. * @param faceIndex The face of the texture to render to in case of cube texture
  12785. * @param requiredWidth The width of the target to render to
  12786. * @param requiredHeight The height of the target to render to
  12787. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12788. * @param depthStencilTexture The depth stencil texture to use to render
  12789. * @param lodLevel defines le lod level to bind to the frame buffer
  12790. */
  12791. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12792. if (lodLevel === void 0) { lodLevel = 0; }
  12793. if (this._currentRenderTarget) {
  12794. this.unBindFramebuffer(this._currentRenderTarget);
  12795. }
  12796. this._currentRenderTarget = texture;
  12797. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12798. var gl = this._gl;
  12799. if (texture.isCube) {
  12800. if (faceIndex === undefined) {
  12801. faceIndex = 0;
  12802. }
  12803. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12804. if (depthStencilTexture) {
  12805. if (depthStencilTexture._generateStencilBuffer) {
  12806. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12807. }
  12808. else {
  12809. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12810. }
  12811. }
  12812. }
  12813. if (this._cachedViewport && !forceFullscreenViewport) {
  12814. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12815. }
  12816. else {
  12817. if (!requiredWidth) {
  12818. requiredWidth = texture.width;
  12819. if (lodLevel) {
  12820. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12821. }
  12822. }
  12823. if (!requiredHeight) {
  12824. requiredHeight = texture.height;
  12825. if (lodLevel) {
  12826. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12827. }
  12828. }
  12829. this._viewport(0, 0, requiredWidth, requiredHeight);
  12830. }
  12831. this.wipeCaches();
  12832. };
  12833. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12834. if (this._currentFramebuffer !== framebuffer) {
  12835. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12836. this._currentFramebuffer = framebuffer;
  12837. }
  12838. };
  12839. /**
  12840. * Unbind the current render target texture from the webGL context
  12841. * @param texture defines the render target texture to unbind
  12842. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12843. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12844. */
  12845. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12846. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12847. this._currentRenderTarget = null;
  12848. // If MSAA, we need to bitblt back to main texture
  12849. var gl = this._gl;
  12850. if (texture._MSAAFramebuffer) {
  12851. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12852. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12853. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12854. }
  12855. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12856. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12857. gl.generateMipmap(gl.TEXTURE_2D);
  12858. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12859. }
  12860. if (onBeforeUnbind) {
  12861. if (texture._MSAAFramebuffer) {
  12862. // Bind the correct framebuffer
  12863. this.bindUnboundFramebuffer(texture._framebuffer);
  12864. }
  12865. onBeforeUnbind();
  12866. }
  12867. this.bindUnboundFramebuffer(null);
  12868. };
  12869. /**
  12870. * Unbind a list of render target textures from the webGL context
  12871. * This is used only when drawBuffer extension or webGL2 are active
  12872. * @param textures defines the render target textures to unbind
  12873. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12874. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12875. */
  12876. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12877. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12878. this._currentRenderTarget = null;
  12879. // If MSAA, we need to bitblt back to main texture
  12880. var gl = this._gl;
  12881. if (textures[0]._MSAAFramebuffer) {
  12882. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12883. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12884. var attachments = textures[0]._attachments;
  12885. if (!attachments) {
  12886. attachments = new Array(textures.length);
  12887. textures[0]._attachments = attachments;
  12888. }
  12889. for (var i = 0; i < textures.length; i++) {
  12890. var texture = textures[i];
  12891. for (var j = 0; j < attachments.length; j++) {
  12892. attachments[j] = gl.NONE;
  12893. }
  12894. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12895. gl.readBuffer(attachments[i]);
  12896. gl.drawBuffers(attachments);
  12897. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12898. }
  12899. for (var i = 0; i < attachments.length; i++) {
  12900. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12901. }
  12902. gl.drawBuffers(attachments);
  12903. }
  12904. for (var i = 0; i < textures.length; i++) {
  12905. var texture = textures[i];
  12906. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12907. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12908. gl.generateMipmap(gl.TEXTURE_2D);
  12909. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12910. }
  12911. }
  12912. if (onBeforeUnbind) {
  12913. if (textures[0]._MSAAFramebuffer) {
  12914. // Bind the correct framebuffer
  12915. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12916. }
  12917. onBeforeUnbind();
  12918. }
  12919. this.bindUnboundFramebuffer(null);
  12920. };
  12921. /**
  12922. * Force the mipmap generation for the given render target texture
  12923. * @param texture defines the render target texture to use
  12924. */
  12925. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12926. if (texture.generateMipMaps) {
  12927. var gl = this._gl;
  12928. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12929. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12930. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12931. }
  12932. };
  12933. /**
  12934. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12935. */
  12936. Engine.prototype.flushFramebuffer = function () {
  12937. this._gl.flush();
  12938. };
  12939. /**
  12940. * Unbind the current render target and bind the default framebuffer
  12941. */
  12942. Engine.prototype.restoreDefaultFramebuffer = function () {
  12943. if (this._currentRenderTarget) {
  12944. this.unBindFramebuffer(this._currentRenderTarget);
  12945. }
  12946. else {
  12947. this.bindUnboundFramebuffer(null);
  12948. }
  12949. if (this._cachedViewport) {
  12950. this.setViewport(this._cachedViewport);
  12951. }
  12952. this.wipeCaches();
  12953. };
  12954. // UBOs
  12955. /**
  12956. * Create an uniform buffer
  12957. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12958. * @param elements defines the content of the uniform buffer
  12959. * @returns the webGL uniform buffer
  12960. */
  12961. Engine.prototype.createUniformBuffer = function (elements) {
  12962. var ubo = this._gl.createBuffer();
  12963. if (!ubo) {
  12964. throw new Error("Unable to create uniform buffer");
  12965. }
  12966. this.bindUniformBuffer(ubo);
  12967. if (elements instanceof Float32Array) {
  12968. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12969. }
  12970. else {
  12971. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12972. }
  12973. this.bindUniformBuffer(null);
  12974. ubo.references = 1;
  12975. return ubo;
  12976. };
  12977. /**
  12978. * Create a dynamic uniform buffer
  12979. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12980. * @param elements defines the content of the uniform buffer
  12981. * @returns the webGL uniform buffer
  12982. */
  12983. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12984. var ubo = this._gl.createBuffer();
  12985. if (!ubo) {
  12986. throw new Error("Unable to create dynamic uniform buffer");
  12987. }
  12988. this.bindUniformBuffer(ubo);
  12989. if (elements instanceof Float32Array) {
  12990. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12991. }
  12992. else {
  12993. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12994. }
  12995. this.bindUniformBuffer(null);
  12996. ubo.references = 1;
  12997. return ubo;
  12998. };
  12999. /**
  13000. * Update an existing uniform buffer
  13001. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13002. * @param uniformBuffer defines the target uniform buffer
  13003. * @param elements defines the content to update
  13004. * @param offset defines the offset in the uniform buffer where update should start
  13005. * @param count defines the size of the data to update
  13006. */
  13007. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13008. this.bindUniformBuffer(uniformBuffer);
  13009. if (offset === undefined) {
  13010. offset = 0;
  13011. }
  13012. if (count === undefined) {
  13013. if (elements instanceof Float32Array) {
  13014. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13015. }
  13016. else {
  13017. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13018. }
  13019. }
  13020. else {
  13021. if (elements instanceof Float32Array) {
  13022. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13023. }
  13024. else {
  13025. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13026. }
  13027. }
  13028. this.bindUniformBuffer(null);
  13029. };
  13030. // VBOs
  13031. Engine.prototype._resetVertexBufferBinding = function () {
  13032. this.bindArrayBuffer(null);
  13033. this._cachedVertexBuffers = null;
  13034. };
  13035. /**
  13036. * Creates a vertex buffer
  13037. * @param data the data for the vertex buffer
  13038. * @returns the new WebGL static buffer
  13039. */
  13040. Engine.prototype.createVertexBuffer = function (data) {
  13041. var vbo = this._gl.createBuffer();
  13042. if (!vbo) {
  13043. throw new Error("Unable to create vertex buffer");
  13044. }
  13045. this.bindArrayBuffer(vbo);
  13046. if (data instanceof Array) {
  13047. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13048. }
  13049. else {
  13050. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13051. }
  13052. this._resetVertexBufferBinding();
  13053. vbo.references = 1;
  13054. return vbo;
  13055. };
  13056. /**
  13057. * Creates a dynamic vertex buffer
  13058. * @param data the data for the dynamic vertex buffer
  13059. * @returns the new WebGL dynamic buffer
  13060. */
  13061. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13062. var vbo = this._gl.createBuffer();
  13063. if (!vbo) {
  13064. throw new Error("Unable to create dynamic vertex buffer");
  13065. }
  13066. this.bindArrayBuffer(vbo);
  13067. if (data instanceof Array) {
  13068. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13069. }
  13070. else {
  13071. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13072. }
  13073. this._resetVertexBufferBinding();
  13074. vbo.references = 1;
  13075. return vbo;
  13076. };
  13077. /**
  13078. * Update a dynamic index buffer
  13079. * @param indexBuffer defines the target index buffer
  13080. * @param indices defines the data to update
  13081. * @param offset defines the offset in the target index buffer where update should start
  13082. */
  13083. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13084. if (offset === void 0) { offset = 0; }
  13085. // Force cache update
  13086. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13087. this.bindIndexBuffer(indexBuffer);
  13088. var arrayBuffer;
  13089. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13090. arrayBuffer = indices;
  13091. }
  13092. else {
  13093. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13094. }
  13095. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13096. this._resetIndexBufferBinding();
  13097. };
  13098. /**
  13099. * Updates a dynamic vertex buffer.
  13100. * @param vertexBuffer the vertex buffer to update
  13101. * @param data the data used to update the vertex buffer
  13102. * @param byteOffset the byte offset of the data
  13103. * @param byteLength the byte length of the data
  13104. */
  13105. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13106. this.bindArrayBuffer(vertexBuffer);
  13107. if (byteOffset === undefined) {
  13108. byteOffset = 0;
  13109. }
  13110. if (byteLength === undefined) {
  13111. if (data instanceof Array) {
  13112. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13113. }
  13114. else {
  13115. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13116. }
  13117. }
  13118. else {
  13119. if (data instanceof Array) {
  13120. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13121. }
  13122. else {
  13123. if (data instanceof ArrayBuffer) {
  13124. data = new Uint8Array(data, byteOffset, byteLength);
  13125. }
  13126. else {
  13127. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13128. }
  13129. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13130. }
  13131. }
  13132. this._resetVertexBufferBinding();
  13133. };
  13134. Engine.prototype._resetIndexBufferBinding = function () {
  13135. this.bindIndexBuffer(null);
  13136. this._cachedIndexBuffer = null;
  13137. };
  13138. /**
  13139. * Creates a new index buffer
  13140. * @param indices defines the content of the index buffer
  13141. * @param updatable defines if the index buffer must be updatable
  13142. * @returns a new webGL buffer
  13143. */
  13144. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13145. var vbo = this._gl.createBuffer();
  13146. if (!vbo) {
  13147. throw new Error("Unable to create index buffer");
  13148. }
  13149. this.bindIndexBuffer(vbo);
  13150. // Check for 32 bits indices
  13151. var arrayBuffer;
  13152. var need32Bits = false;
  13153. if (indices instanceof Uint16Array) {
  13154. arrayBuffer = indices;
  13155. }
  13156. else {
  13157. //check 32 bit support
  13158. if (this._caps.uintIndices) {
  13159. if (indices instanceof Uint32Array) {
  13160. arrayBuffer = indices;
  13161. need32Bits = true;
  13162. }
  13163. else {
  13164. //number[] or Int32Array, check if 32 bit is necessary
  13165. for (var index = 0; index < indices.length; index++) {
  13166. if (indices[index] > 65535) {
  13167. need32Bits = true;
  13168. break;
  13169. }
  13170. }
  13171. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13172. }
  13173. }
  13174. else {
  13175. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13176. arrayBuffer = new Uint16Array(indices);
  13177. }
  13178. }
  13179. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13180. this._resetIndexBufferBinding();
  13181. vbo.references = 1;
  13182. vbo.is32Bits = need32Bits;
  13183. return vbo;
  13184. };
  13185. /**
  13186. * Bind a webGL buffer to the webGL context
  13187. * @param buffer defines the buffer to bind
  13188. */
  13189. Engine.prototype.bindArrayBuffer = function (buffer) {
  13190. if (!this._vaoRecordInProgress) {
  13191. this._unbindVertexArrayObject();
  13192. }
  13193. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13194. };
  13195. /**
  13196. * Bind an uniform buffer to the current webGL context
  13197. * @param buffer defines the buffer to bind
  13198. */
  13199. Engine.prototype.bindUniformBuffer = function (buffer) {
  13200. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13201. };
  13202. /**
  13203. * Bind a buffer to the current webGL context at a given location
  13204. * @param buffer defines the buffer to bind
  13205. * @param location defines the index where to bind the buffer
  13206. */
  13207. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13208. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13209. };
  13210. /**
  13211. * Bind a specific block at a given index in a specific shader program
  13212. * @param shaderProgram defines the shader program
  13213. * @param blockName defines the block name
  13214. * @param index defines the index where to bind the block
  13215. */
  13216. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13217. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13218. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13219. };
  13220. ;
  13221. Engine.prototype.bindIndexBuffer = function (buffer) {
  13222. if (!this._vaoRecordInProgress) {
  13223. this._unbindVertexArrayObject();
  13224. }
  13225. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13226. };
  13227. Engine.prototype.bindBuffer = function (buffer, target) {
  13228. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13229. this._gl.bindBuffer(target, buffer);
  13230. this._currentBoundBuffer[target] = buffer;
  13231. }
  13232. };
  13233. /**
  13234. * update the bound buffer with the given data
  13235. * @param data defines the data to update
  13236. */
  13237. Engine.prototype.updateArrayBuffer = function (data) {
  13238. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13239. };
  13240. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13241. var pointer = this._currentBufferPointers[indx];
  13242. var changed = false;
  13243. if (!pointer.active) {
  13244. changed = true;
  13245. pointer.active = true;
  13246. pointer.index = indx;
  13247. pointer.size = size;
  13248. pointer.type = type;
  13249. pointer.normalized = normalized;
  13250. pointer.stride = stride;
  13251. pointer.offset = offset;
  13252. pointer.buffer = buffer;
  13253. }
  13254. else {
  13255. if (pointer.buffer !== buffer) {
  13256. pointer.buffer = buffer;
  13257. changed = true;
  13258. }
  13259. if (pointer.size !== size) {
  13260. pointer.size = size;
  13261. changed = true;
  13262. }
  13263. if (pointer.type !== type) {
  13264. pointer.type = type;
  13265. changed = true;
  13266. }
  13267. if (pointer.normalized !== normalized) {
  13268. pointer.normalized = normalized;
  13269. changed = true;
  13270. }
  13271. if (pointer.stride !== stride) {
  13272. pointer.stride = stride;
  13273. changed = true;
  13274. }
  13275. if (pointer.offset !== offset) {
  13276. pointer.offset = offset;
  13277. changed = true;
  13278. }
  13279. }
  13280. if (changed || this._vaoRecordInProgress) {
  13281. this.bindArrayBuffer(buffer);
  13282. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13283. }
  13284. };
  13285. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13286. if (indexBuffer == null) {
  13287. return;
  13288. }
  13289. if (this._cachedIndexBuffer !== indexBuffer) {
  13290. this._cachedIndexBuffer = indexBuffer;
  13291. this.bindIndexBuffer(indexBuffer);
  13292. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13293. }
  13294. };
  13295. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13296. var attributes = effect.getAttributesNames();
  13297. if (!this._vaoRecordInProgress) {
  13298. this._unbindVertexArrayObject();
  13299. }
  13300. this.unbindAllAttributes();
  13301. for (var index = 0; index < attributes.length; index++) {
  13302. var order = effect.getAttributeLocation(index);
  13303. if (order >= 0) {
  13304. var vertexBuffer = vertexBuffers[attributes[index]];
  13305. if (!vertexBuffer) {
  13306. continue;
  13307. }
  13308. this._gl.enableVertexAttribArray(order);
  13309. if (!this._vaoRecordInProgress) {
  13310. this._vertexAttribArraysEnabled[order] = true;
  13311. }
  13312. var buffer = vertexBuffer.getBuffer();
  13313. if (buffer) {
  13314. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13315. if (vertexBuffer.getIsInstanced()) {
  13316. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13317. if (!this._vaoRecordInProgress) {
  13318. this._currentInstanceLocations.push(order);
  13319. this._currentInstanceBuffers.push(buffer);
  13320. }
  13321. }
  13322. }
  13323. }
  13324. }
  13325. };
  13326. /**
  13327. * Records a vertex array object
  13328. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13329. * @param vertexBuffers defines the list of vertex buffers to store
  13330. * @param indexBuffer defines the index buffer to store
  13331. * @param effect defines the effect to store
  13332. * @returns the new vertex array object
  13333. */
  13334. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13335. var vao = this._gl.createVertexArray();
  13336. this._vaoRecordInProgress = true;
  13337. this._gl.bindVertexArray(vao);
  13338. this._mustWipeVertexAttributes = true;
  13339. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13340. this.bindIndexBuffer(indexBuffer);
  13341. this._vaoRecordInProgress = false;
  13342. this._gl.bindVertexArray(null);
  13343. return vao;
  13344. };
  13345. /**
  13346. * Bind a specific vertex array object
  13347. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13348. * @param vertexArrayObject defines the vertex array object to bind
  13349. * @param indexBuffer defines the index buffer to bind
  13350. */
  13351. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13352. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13353. this._cachedVertexArrayObject = vertexArrayObject;
  13354. this._gl.bindVertexArray(vertexArrayObject);
  13355. this._cachedVertexBuffers = null;
  13356. this._cachedIndexBuffer = null;
  13357. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13358. this._mustWipeVertexAttributes = true;
  13359. }
  13360. };
  13361. /**
  13362. * Bind webGl buffers directly to the webGL context
  13363. * @param vertexBuffer defines the vertex buffer to bind
  13364. * @param indexBuffer defines the index buffer to bind
  13365. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13366. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13367. * @param effect defines the effect associated with the vertex buffer
  13368. */
  13369. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13370. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13371. this._cachedVertexBuffers = vertexBuffer;
  13372. this._cachedEffectForVertexBuffers = effect;
  13373. var attributesCount = effect.getAttributesCount();
  13374. this._unbindVertexArrayObject();
  13375. this.unbindAllAttributes();
  13376. var offset = 0;
  13377. for (var index = 0; index < attributesCount; index++) {
  13378. if (index < vertexDeclaration.length) {
  13379. var order = effect.getAttributeLocation(index);
  13380. if (order >= 0) {
  13381. this._gl.enableVertexAttribArray(order);
  13382. this._vertexAttribArraysEnabled[order] = true;
  13383. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13384. }
  13385. offset += vertexDeclaration[index] * 4;
  13386. }
  13387. }
  13388. }
  13389. this._bindIndexBufferWithCache(indexBuffer);
  13390. };
  13391. Engine.prototype._unbindVertexArrayObject = function () {
  13392. if (!this._cachedVertexArrayObject) {
  13393. return;
  13394. }
  13395. this._cachedVertexArrayObject = null;
  13396. this._gl.bindVertexArray(null);
  13397. };
  13398. /**
  13399. * Bind a list of vertex buffers to the webGL context
  13400. * @param vertexBuffers defines the list of vertex buffers to bind
  13401. * @param indexBuffer defines the index buffer to bind
  13402. * @param effect defines the effect associated with the vertex buffers
  13403. */
  13404. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13405. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13406. this._cachedVertexBuffers = vertexBuffers;
  13407. this._cachedEffectForVertexBuffers = effect;
  13408. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13409. }
  13410. this._bindIndexBufferWithCache(indexBuffer);
  13411. };
  13412. /**
  13413. * Unbind all instance attributes
  13414. */
  13415. Engine.prototype.unbindInstanceAttributes = function () {
  13416. var boundBuffer;
  13417. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13418. var instancesBuffer = this._currentInstanceBuffers[i];
  13419. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13420. boundBuffer = instancesBuffer;
  13421. this.bindArrayBuffer(instancesBuffer);
  13422. }
  13423. var offsetLocation = this._currentInstanceLocations[i];
  13424. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13425. }
  13426. this._currentInstanceBuffers.length = 0;
  13427. this._currentInstanceLocations.length = 0;
  13428. };
  13429. /**
  13430. * Release and free the memory of a vertex array object
  13431. * @param vao defines the vertex array object to delete
  13432. */
  13433. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13434. this._gl.deleteVertexArray(vao);
  13435. };
  13436. /** @hidden */
  13437. Engine.prototype._releaseBuffer = function (buffer) {
  13438. buffer.references--;
  13439. if (buffer.references === 0) {
  13440. this._gl.deleteBuffer(buffer);
  13441. return true;
  13442. }
  13443. return false;
  13444. };
  13445. /**
  13446. * Creates a webGL buffer to use with instanciation
  13447. * @param capacity defines the size of the buffer
  13448. * @returns the webGL buffer
  13449. */
  13450. Engine.prototype.createInstancesBuffer = function (capacity) {
  13451. var buffer = this._gl.createBuffer();
  13452. if (!buffer) {
  13453. throw new Error("Unable to create instance buffer");
  13454. }
  13455. buffer.capacity = capacity;
  13456. this.bindArrayBuffer(buffer);
  13457. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13458. return buffer;
  13459. };
  13460. /**
  13461. * Delete a webGL buffer used with instanciation
  13462. * @param buffer defines the webGL buffer to delete
  13463. */
  13464. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13465. this._gl.deleteBuffer(buffer);
  13466. };
  13467. /**
  13468. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13469. * @param instancesBuffer defines the webGL buffer to update and bind
  13470. * @param data defines the data to store in the buffer
  13471. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13472. */
  13473. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13474. this.bindArrayBuffer(instancesBuffer);
  13475. if (data) {
  13476. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13477. }
  13478. if (offsetLocations[0].index !== undefined) {
  13479. var stride = 0;
  13480. for (var i = 0; i < offsetLocations.length; i++) {
  13481. var ai = offsetLocations[i];
  13482. stride += ai.attributeSize * 4;
  13483. }
  13484. for (var i = 0; i < offsetLocations.length; i++) {
  13485. var ai = offsetLocations[i];
  13486. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13487. this._gl.enableVertexAttribArray(ai.index);
  13488. this._vertexAttribArraysEnabled[ai.index] = true;
  13489. }
  13490. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13491. this._gl.vertexAttribDivisor(ai.index, 1);
  13492. this._currentInstanceLocations.push(ai.index);
  13493. this._currentInstanceBuffers.push(instancesBuffer);
  13494. }
  13495. }
  13496. else {
  13497. for (var index = 0; index < 4; index++) {
  13498. var offsetLocation = offsetLocations[index];
  13499. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13500. this._gl.enableVertexAttribArray(offsetLocation);
  13501. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13502. }
  13503. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13504. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13505. this._currentInstanceLocations.push(offsetLocation);
  13506. this._currentInstanceBuffers.push(instancesBuffer);
  13507. }
  13508. }
  13509. };
  13510. /**
  13511. * Apply all cached states (depth, culling, stencil and alpha)
  13512. */
  13513. Engine.prototype.applyStates = function () {
  13514. this._depthCullingState.apply(this._gl);
  13515. this._stencilState.apply(this._gl);
  13516. this._alphaState.apply(this._gl);
  13517. };
  13518. /**
  13519. * Send a draw order
  13520. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13521. * @param indexStart defines the starting index
  13522. * @param indexCount defines the number of index to draw
  13523. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13524. */
  13525. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13526. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13527. };
  13528. /**
  13529. * Draw a list of points
  13530. * @param verticesStart defines the index of first vertex to draw
  13531. * @param verticesCount defines the count of vertices to draw
  13532. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13533. */
  13534. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13535. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13536. };
  13537. /**
  13538. * Draw a list of unindexed primitives
  13539. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13540. * @param verticesStart defines the index of first vertex to draw
  13541. * @param verticesCount defines the count of vertices to draw
  13542. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13543. */
  13544. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13545. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13546. };
  13547. /**
  13548. * Draw a list of indexed primitives
  13549. * @param fillMode defines the primitive to use
  13550. * @param indexStart defines the starting index
  13551. * @param indexCount defines the number of index to draw
  13552. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13553. */
  13554. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13555. // Apply states
  13556. this.applyStates();
  13557. this._drawCalls.addCount(1, false);
  13558. // Render
  13559. var drawMode = this._drawMode(fillMode);
  13560. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13561. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13562. if (instancesCount) {
  13563. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13564. }
  13565. else {
  13566. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13567. }
  13568. };
  13569. /**
  13570. * Draw a list of unindexed primitives
  13571. * @param fillMode defines the primitive to use
  13572. * @param verticesStart defines the index of first vertex to draw
  13573. * @param verticesCount defines the count of vertices to draw
  13574. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13575. */
  13576. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13577. // Apply states
  13578. this.applyStates();
  13579. this._drawCalls.addCount(1, false);
  13580. var drawMode = this._drawMode(fillMode);
  13581. if (instancesCount) {
  13582. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13583. }
  13584. else {
  13585. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13586. }
  13587. };
  13588. Engine.prototype._drawMode = function (fillMode) {
  13589. switch (fillMode) {
  13590. // Triangle views
  13591. case BABYLON.Material.TriangleFillMode:
  13592. return this._gl.TRIANGLES;
  13593. case BABYLON.Material.PointFillMode:
  13594. return this._gl.POINTS;
  13595. case BABYLON.Material.WireFrameFillMode:
  13596. return this._gl.LINES;
  13597. // Draw modes
  13598. case BABYLON.Material.PointListDrawMode:
  13599. return this._gl.POINTS;
  13600. case BABYLON.Material.LineListDrawMode:
  13601. return this._gl.LINES;
  13602. case BABYLON.Material.LineLoopDrawMode:
  13603. return this._gl.LINE_LOOP;
  13604. case BABYLON.Material.LineStripDrawMode:
  13605. return this._gl.LINE_STRIP;
  13606. case BABYLON.Material.TriangleStripDrawMode:
  13607. return this._gl.TRIANGLE_STRIP;
  13608. case BABYLON.Material.TriangleFanDrawMode:
  13609. return this._gl.TRIANGLE_FAN;
  13610. default:
  13611. return this._gl.TRIANGLES;
  13612. }
  13613. };
  13614. // Shaders
  13615. /** @hidden */
  13616. Engine.prototype._releaseEffect = function (effect) {
  13617. if (this._compiledEffects[effect._key]) {
  13618. delete this._compiledEffects[effect._key];
  13619. this._deleteProgram(effect.getProgram());
  13620. }
  13621. };
  13622. /** @hidden */
  13623. Engine.prototype._deleteProgram = function (program) {
  13624. if (program) {
  13625. program.__SPECTOR_rebuildProgram = null;
  13626. if (program.transformFeedback) {
  13627. this.deleteTransformFeedback(program.transformFeedback);
  13628. program.transformFeedback = null;
  13629. }
  13630. this._gl.deleteProgram(program);
  13631. }
  13632. };
  13633. /**
  13634. * Create a new effect (used to store vertex/fragment shaders)
  13635. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13636. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13637. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13638. * @param samplers defines an array of string used to represent textures
  13639. * @param defines defines the string containing the defines to use to compile the shaders
  13640. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13641. * @param onCompiled defines a function to call when the effect creation is successful
  13642. * @param onError defines a function to call when the effect creation has failed
  13643. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13644. * @returns the new Effect
  13645. */
  13646. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13647. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13648. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13649. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13650. if (this._compiledEffects[name]) {
  13651. var compiledEffect = this._compiledEffects[name];
  13652. if (onCompiled && compiledEffect.isReady()) {
  13653. onCompiled(compiledEffect);
  13654. }
  13655. return compiledEffect;
  13656. }
  13657. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13658. effect._key = name;
  13659. this._compiledEffects[name] = effect;
  13660. return effect;
  13661. };
  13662. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13663. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13664. };
  13665. ;
  13666. Engine.prototype._compileRawShader = function (source, type) {
  13667. var gl = this._gl;
  13668. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13669. gl.shaderSource(shader, source);
  13670. gl.compileShader(shader);
  13671. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13672. var log = gl.getShaderInfoLog(shader);
  13673. if (log) {
  13674. throw new Error(log);
  13675. }
  13676. }
  13677. if (!shader) {
  13678. throw new Error("Something went wrong while compile the shader.");
  13679. }
  13680. return shader;
  13681. };
  13682. ;
  13683. /**
  13684. * Directly creates a webGL program
  13685. * @param vertexCode defines the vertex shader code to use
  13686. * @param fragmentCode defines the fragment shader code to use
  13687. * @param context defines the webGL context to use (if not set, the current one will be used)
  13688. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13689. * @returns the new webGL program
  13690. */
  13691. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13692. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13693. context = context || this._gl;
  13694. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13695. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13696. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13697. };
  13698. /**
  13699. * Creates a webGL program
  13700. * @param vertexCode defines the vertex shader code to use
  13701. * @param fragmentCode defines the fragment shader code to use
  13702. * @param defines defines the string containing the defines to use to compile the shaders
  13703. * @param context defines the webGL context to use (if not set, the current one will be used)
  13704. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13705. * @returns the new webGL program
  13706. */
  13707. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13708. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13709. context = context || this._gl;
  13710. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13711. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13712. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13713. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13714. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13715. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13716. return program;
  13717. };
  13718. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13719. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13720. var shaderProgram = context.createProgram();
  13721. if (!shaderProgram) {
  13722. throw new Error("Unable to create program");
  13723. }
  13724. context.attachShader(shaderProgram, vertexShader);
  13725. context.attachShader(shaderProgram, fragmentShader);
  13726. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13727. var transformFeedback = this.createTransformFeedback();
  13728. this.bindTransformFeedback(transformFeedback);
  13729. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13730. shaderProgram.transformFeedback = transformFeedback;
  13731. }
  13732. context.linkProgram(shaderProgram);
  13733. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13734. this.bindTransformFeedback(null);
  13735. }
  13736. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13737. if (!linked) {
  13738. var error = context.getProgramInfoLog(shaderProgram);
  13739. if (error) {
  13740. throw new Error(error);
  13741. }
  13742. }
  13743. if (this.validateShaderPrograms) {
  13744. context.validateProgram(shaderProgram);
  13745. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13746. if (!validated) {
  13747. var error = context.getProgramInfoLog(shaderProgram);
  13748. if (error) {
  13749. throw new Error(error);
  13750. }
  13751. }
  13752. }
  13753. context.deleteShader(vertexShader);
  13754. context.deleteShader(fragmentShader);
  13755. return shaderProgram;
  13756. };
  13757. /**
  13758. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13759. * @param shaderProgram defines the webGL program to use
  13760. * @param uniformsNames defines the list of uniform names
  13761. * @returns an array of webGL uniform locations
  13762. */
  13763. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13764. var results = new Array();
  13765. for (var index = 0; index < uniformsNames.length; index++) {
  13766. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13767. }
  13768. return results;
  13769. };
  13770. /**
  13771. * Gets the lsit of active attributes for a given webGL program
  13772. * @param shaderProgram defines the webGL program to use
  13773. * @param attributesNames defines the list of attribute names to get
  13774. * @returns an array of indices indicating the offset of each attribute
  13775. */
  13776. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13777. var results = [];
  13778. for (var index = 0; index < attributesNames.length; index++) {
  13779. try {
  13780. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13781. }
  13782. catch (e) {
  13783. results.push(-1);
  13784. }
  13785. }
  13786. return results;
  13787. };
  13788. /**
  13789. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13790. * @param effect defines the effect to activate
  13791. */
  13792. Engine.prototype.enableEffect = function (effect) {
  13793. if (!effect || effect === this._currentEffect) {
  13794. return;
  13795. }
  13796. // Use program
  13797. this.bindSamplers(effect);
  13798. this._currentEffect = effect;
  13799. if (effect.onBind) {
  13800. effect.onBind(effect);
  13801. }
  13802. if (effect._onBindObservable) {
  13803. effect._onBindObservable.notifyObservers(effect);
  13804. }
  13805. };
  13806. /**
  13807. * Set the value of an uniform to an array of int32
  13808. * @param uniform defines the webGL uniform location where to store the value
  13809. * @param array defines the array of int32 to store
  13810. */
  13811. Engine.prototype.setIntArray = function (uniform, array) {
  13812. if (!uniform)
  13813. return;
  13814. this._gl.uniform1iv(uniform, array);
  13815. };
  13816. /**
  13817. * Set the value of an uniform to an array of int32 (stored as vec2)
  13818. * @param uniform defines the webGL uniform location where to store the value
  13819. * @param array defines the array of int32 to store
  13820. */
  13821. Engine.prototype.setIntArray2 = function (uniform, array) {
  13822. if (!uniform || array.length % 2 !== 0)
  13823. return;
  13824. this._gl.uniform2iv(uniform, array);
  13825. };
  13826. /**
  13827. * Set the value of an uniform to an array of int32 (stored as vec3)
  13828. * @param uniform defines the webGL uniform location where to store the value
  13829. * @param array defines the array of int32 to store
  13830. */
  13831. Engine.prototype.setIntArray3 = function (uniform, array) {
  13832. if (!uniform || array.length % 3 !== 0)
  13833. return;
  13834. this._gl.uniform3iv(uniform, array);
  13835. };
  13836. /**
  13837. * Set the value of an uniform to an array of int32 (stored as vec4)
  13838. * @param uniform defines the webGL uniform location where to store the value
  13839. * @param array defines the array of int32 to store
  13840. */
  13841. Engine.prototype.setIntArray4 = function (uniform, array) {
  13842. if (!uniform || array.length % 4 !== 0)
  13843. return;
  13844. this._gl.uniform4iv(uniform, array);
  13845. };
  13846. /**
  13847. * Set the value of an uniform to an array of float32
  13848. * @param uniform defines the webGL uniform location where to store the value
  13849. * @param array defines the array of float32 to store
  13850. */
  13851. Engine.prototype.setFloatArray = function (uniform, array) {
  13852. if (!uniform)
  13853. return;
  13854. this._gl.uniform1fv(uniform, array);
  13855. };
  13856. /**
  13857. * Set the value of an uniform to an array of float32 (stored as vec2)
  13858. * @param uniform defines the webGL uniform location where to store the value
  13859. * @param array defines the array of float32 to store
  13860. */
  13861. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13862. if (!uniform || array.length % 2 !== 0)
  13863. return;
  13864. this._gl.uniform2fv(uniform, array);
  13865. };
  13866. /**
  13867. * Set the value of an uniform to an array of float32 (stored as vec3)
  13868. * @param uniform defines the webGL uniform location where to store the value
  13869. * @param array defines the array of float32 to store
  13870. */
  13871. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13872. if (!uniform || array.length % 3 !== 0)
  13873. return;
  13874. this._gl.uniform3fv(uniform, array);
  13875. };
  13876. /**
  13877. * Set the value of an uniform to an array of float32 (stored as vec4)
  13878. * @param uniform defines the webGL uniform location where to store the value
  13879. * @param array defines the array of float32 to store
  13880. */
  13881. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13882. if (!uniform || array.length % 4 !== 0)
  13883. return;
  13884. this._gl.uniform4fv(uniform, array);
  13885. };
  13886. /**
  13887. * Set the value of an uniform to an array of number
  13888. * @param uniform defines the webGL uniform location where to store the value
  13889. * @param array defines the array of number to store
  13890. */
  13891. Engine.prototype.setArray = function (uniform, array) {
  13892. if (!uniform)
  13893. return;
  13894. this._gl.uniform1fv(uniform, array);
  13895. };
  13896. /**
  13897. * Set the value of an uniform to an array of number (stored as vec2)
  13898. * @param uniform defines the webGL uniform location where to store the value
  13899. * @param array defines the array of number to store
  13900. */
  13901. Engine.prototype.setArray2 = function (uniform, array) {
  13902. if (!uniform || array.length % 2 !== 0)
  13903. return;
  13904. this._gl.uniform2fv(uniform, array);
  13905. };
  13906. /**
  13907. * Set the value of an uniform to an array of number (stored as vec3)
  13908. * @param uniform defines the webGL uniform location where to store the value
  13909. * @param array defines the array of number to store
  13910. */
  13911. Engine.prototype.setArray3 = function (uniform, array) {
  13912. if (!uniform || array.length % 3 !== 0)
  13913. return;
  13914. this._gl.uniform3fv(uniform, array);
  13915. };
  13916. /**
  13917. * Set the value of an uniform to an array of number (stored as vec4)
  13918. * @param uniform defines the webGL uniform location where to store the value
  13919. * @param array defines the array of number to store
  13920. */
  13921. Engine.prototype.setArray4 = function (uniform, array) {
  13922. if (!uniform || array.length % 4 !== 0)
  13923. return;
  13924. this._gl.uniform4fv(uniform, array);
  13925. };
  13926. /**
  13927. * Set the value of an uniform to an array of float32 (stored as matrices)
  13928. * @param uniform defines the webGL uniform location where to store the value
  13929. * @param matrices defines the array of float32 to store
  13930. */
  13931. Engine.prototype.setMatrices = function (uniform, matrices) {
  13932. if (!uniform)
  13933. return;
  13934. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13935. };
  13936. /**
  13937. * Set the value of an uniform to a matrix
  13938. * @param uniform defines the webGL uniform location where to store the value
  13939. * @param matrix defines the matrix to store
  13940. */
  13941. Engine.prototype.setMatrix = function (uniform, matrix) {
  13942. if (!uniform)
  13943. return;
  13944. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13945. };
  13946. /**
  13947. * Set the value of an uniform to a matrix (3x3)
  13948. * @param uniform defines the webGL uniform location where to store the value
  13949. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13950. */
  13951. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13952. if (!uniform)
  13953. return;
  13954. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13955. };
  13956. /**
  13957. * Set the value of an uniform to a matrix (2x2)
  13958. * @param uniform defines the webGL uniform location where to store the value
  13959. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13960. */
  13961. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13962. if (!uniform)
  13963. return;
  13964. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13965. };
  13966. /**
  13967. * Set the value of an uniform to a number (int)
  13968. * @param uniform defines the webGL uniform location where to store the value
  13969. * @param value defines the int number to store
  13970. */
  13971. Engine.prototype.setInt = function (uniform, value) {
  13972. if (!uniform)
  13973. return;
  13974. this._gl.uniform1i(uniform, value);
  13975. };
  13976. /**
  13977. * Set the value of an uniform to a number (float)
  13978. * @param uniform defines the webGL uniform location where to store the value
  13979. * @param value defines the float number to store
  13980. */
  13981. Engine.prototype.setFloat = function (uniform, value) {
  13982. if (!uniform)
  13983. return;
  13984. this._gl.uniform1f(uniform, value);
  13985. };
  13986. /**
  13987. * Set the value of an uniform to a vec2
  13988. * @param uniform defines the webGL uniform location where to store the value
  13989. * @param x defines the 1st component of the value
  13990. * @param y defines the 2nd component of the value
  13991. */
  13992. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13993. if (!uniform)
  13994. return;
  13995. this._gl.uniform2f(uniform, x, y);
  13996. };
  13997. /**
  13998. * Set the value of an uniform to a vec3
  13999. * @param uniform defines the webGL uniform location where to store the value
  14000. * @param x defines the 1st component of the value
  14001. * @param y defines the 2nd component of the value
  14002. * @param z defines the 3rd component of the value
  14003. */
  14004. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14005. if (!uniform)
  14006. return;
  14007. this._gl.uniform3f(uniform, x, y, z);
  14008. };
  14009. /**
  14010. * Set the value of an uniform to a boolean
  14011. * @param uniform defines the webGL uniform location where to store the value
  14012. * @param bool defines the boolean to store
  14013. */
  14014. Engine.prototype.setBool = function (uniform, bool) {
  14015. if (!uniform)
  14016. return;
  14017. this._gl.uniform1i(uniform, bool);
  14018. };
  14019. /**
  14020. * Set the value of an uniform to a vec4
  14021. * @param uniform defines the webGL uniform location where to store the value
  14022. * @param x defines the 1st component of the value
  14023. * @param y defines the 2nd component of the value
  14024. * @param z defines the 3rd component of the value
  14025. * @param w defines the 4th component of the value
  14026. */
  14027. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14028. if (!uniform)
  14029. return;
  14030. this._gl.uniform4f(uniform, x, y, z, w);
  14031. };
  14032. /**
  14033. * Set the value of an uniform to a Color3
  14034. * @param uniform defines the webGL uniform location where to store the value
  14035. * @param color3 defines the color to store
  14036. */
  14037. Engine.prototype.setColor3 = function (uniform, color3) {
  14038. if (!uniform)
  14039. return;
  14040. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14041. };
  14042. /**
  14043. * Set the value of an uniform to a Color3 and an alpha value
  14044. * @param uniform defines the webGL uniform location where to store the value
  14045. * @param color3 defines the color to store
  14046. * @param alpha defines the alpha component to store
  14047. */
  14048. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14049. if (!uniform)
  14050. return;
  14051. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14052. };
  14053. /**
  14054. * Sets a Color4 on a uniform variable
  14055. * @param uniform defines the uniform location
  14056. * @param color4 defines the value to be set
  14057. */
  14058. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14059. if (!uniform)
  14060. return;
  14061. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14062. };
  14063. // States
  14064. /**
  14065. * Set various states to the webGL context
  14066. * @param culling defines backface culling state
  14067. * @param zOffset defines the value to apply to zOffset (0 by default)
  14068. * @param force defines if states must be applied even if cache is up to date
  14069. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14070. */
  14071. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14072. if (zOffset === void 0) { zOffset = 0; }
  14073. if (reverseSide === void 0) { reverseSide = false; }
  14074. // Culling
  14075. if (this._depthCullingState.cull !== culling || force) {
  14076. this._depthCullingState.cull = culling;
  14077. }
  14078. // Cull face
  14079. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14080. if (this._depthCullingState.cullFace !== cullFace || force) {
  14081. this._depthCullingState.cullFace = cullFace;
  14082. }
  14083. // Z offset
  14084. this.setZOffset(zOffset);
  14085. // Front face
  14086. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14087. if (this._depthCullingState.frontFace !== frontFace || force) {
  14088. this._depthCullingState.frontFace = frontFace;
  14089. }
  14090. };
  14091. /**
  14092. * Set the z offset to apply to current rendering
  14093. * @param value defines the offset to apply
  14094. */
  14095. Engine.prototype.setZOffset = function (value) {
  14096. this._depthCullingState.zOffset = value;
  14097. };
  14098. /**
  14099. * Gets the current value of the zOffset
  14100. * @returns the current zOffset state
  14101. */
  14102. Engine.prototype.getZOffset = function () {
  14103. return this._depthCullingState.zOffset;
  14104. };
  14105. /**
  14106. * Enable or disable depth buffering
  14107. * @param enable defines the state to set
  14108. */
  14109. Engine.prototype.setDepthBuffer = function (enable) {
  14110. this._depthCullingState.depthTest = enable;
  14111. };
  14112. /**
  14113. * Gets a boolean indicating if depth writing is enabled
  14114. * @returns the current depth writing state
  14115. */
  14116. Engine.prototype.getDepthWrite = function () {
  14117. return this._depthCullingState.depthMask;
  14118. };
  14119. /**
  14120. * Enable or disable depth writing
  14121. * @param enable defines the state to set
  14122. */
  14123. Engine.prototype.setDepthWrite = function (enable) {
  14124. this._depthCullingState.depthMask = enable;
  14125. };
  14126. /**
  14127. * Enable or disable color writing
  14128. * @param enable defines the state to set
  14129. */
  14130. Engine.prototype.setColorWrite = function (enable) {
  14131. this._gl.colorMask(enable, enable, enable, enable);
  14132. this._colorWrite = enable;
  14133. };
  14134. /**
  14135. * Gets a boolean indicating if color writing is enabled
  14136. * @returns the current color writing state
  14137. */
  14138. Engine.prototype.getColorWrite = function () {
  14139. return this._colorWrite;
  14140. };
  14141. /**
  14142. * Sets alpha constants used by some alpha blending modes
  14143. * @param r defines the red component
  14144. * @param g defines the green component
  14145. * @param b defines the blue component
  14146. * @param a defines the alpha component
  14147. */
  14148. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14149. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14150. };
  14151. /**
  14152. * Sets the current alpha mode
  14153. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14154. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14155. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14156. */
  14157. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14158. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14159. if (this._alphaMode === mode) {
  14160. return;
  14161. }
  14162. switch (mode) {
  14163. case Engine.ALPHA_DISABLE:
  14164. this._alphaState.alphaBlend = false;
  14165. break;
  14166. case Engine.ALPHA_PREMULTIPLIED:
  14167. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14168. this._alphaState.alphaBlend = true;
  14169. break;
  14170. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14171. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14172. this._alphaState.alphaBlend = true;
  14173. break;
  14174. case Engine.ALPHA_COMBINE:
  14175. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14176. this._alphaState.alphaBlend = true;
  14177. break;
  14178. case Engine.ALPHA_ONEONE:
  14179. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14180. this._alphaState.alphaBlend = true;
  14181. break;
  14182. case Engine.ALPHA_ADD:
  14183. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14184. this._alphaState.alphaBlend = true;
  14185. break;
  14186. case Engine.ALPHA_SUBTRACT:
  14187. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14188. this._alphaState.alphaBlend = true;
  14189. break;
  14190. case Engine.ALPHA_MULTIPLY:
  14191. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14192. this._alphaState.alphaBlend = true;
  14193. break;
  14194. case Engine.ALPHA_MAXIMIZED:
  14195. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14196. this._alphaState.alphaBlend = true;
  14197. break;
  14198. case Engine.ALPHA_INTERPOLATE:
  14199. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14200. this._alphaState.alphaBlend = true;
  14201. break;
  14202. case Engine.ALPHA_SCREENMODE:
  14203. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14204. this._alphaState.alphaBlend = true;
  14205. break;
  14206. }
  14207. if (!noDepthWriteChange) {
  14208. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14209. }
  14210. this._alphaMode = mode;
  14211. };
  14212. /**
  14213. * Gets the current alpha mode
  14214. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14215. * @returns the current alpha mode
  14216. */
  14217. Engine.prototype.getAlphaMode = function () {
  14218. return this._alphaMode;
  14219. };
  14220. // Textures
  14221. /**
  14222. * Clears the list of texture accessible through engine.
  14223. * This can help preventing texture load conflict due to name collision.
  14224. */
  14225. Engine.prototype.clearInternalTexturesCache = function () {
  14226. this._internalTexturesCache = [];
  14227. };
  14228. /**
  14229. * Force the entire cache to be cleared
  14230. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14231. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14232. */
  14233. Engine.prototype.wipeCaches = function (bruteForce) {
  14234. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14235. return;
  14236. }
  14237. this._currentEffect = null;
  14238. this._unpackFlipYCached = null;
  14239. this._viewportCached.x = 0;
  14240. this._viewportCached.y = 0;
  14241. this._viewportCached.z = 0;
  14242. this._viewportCached.w = 0;
  14243. if (bruteForce) {
  14244. this.resetTextureCache();
  14245. this._currentProgram = null;
  14246. this._stencilState.reset();
  14247. this._depthCullingState.reset();
  14248. this.setDepthFunctionToLessOrEqual();
  14249. this._alphaState.reset();
  14250. }
  14251. this._resetVertexBufferBinding();
  14252. this._cachedIndexBuffer = null;
  14253. this._cachedEffectForVertexBuffers = null;
  14254. this._unbindVertexArrayObject();
  14255. this.bindIndexBuffer(null);
  14256. };
  14257. /**
  14258. * Set the compressed texture format to use, based on the formats you have, and the formats
  14259. * supported by the hardware / browser.
  14260. *
  14261. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14262. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14263. * to API arguments needed to compressed textures. This puts the burden on the container
  14264. * generator to house the arcane code for determining these for current & future formats.
  14265. *
  14266. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14267. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14268. *
  14269. * Note: The result of this call is not taken into account when a texture is base64.
  14270. *
  14271. * @param formatsAvailable defines the list of those format families you have created
  14272. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14273. *
  14274. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14275. * @returns The extension selected.
  14276. */
  14277. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14278. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14279. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14280. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14281. return this._textureFormatInUse = this._texturesSupported[i];
  14282. }
  14283. }
  14284. }
  14285. // actively set format to nothing, to allow this to be called more than once
  14286. // and possibly fail the 2nd time
  14287. this._textureFormatInUse = null;
  14288. return null;
  14289. };
  14290. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14291. var gl = this._gl;
  14292. var magFilter = gl.NEAREST;
  14293. var minFilter = gl.NEAREST;
  14294. switch (samplingMode) {
  14295. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14296. magFilter = gl.LINEAR;
  14297. if (generateMipMaps) {
  14298. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14299. }
  14300. else {
  14301. minFilter = gl.LINEAR;
  14302. }
  14303. break;
  14304. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14305. magFilter = gl.LINEAR;
  14306. if (generateMipMaps) {
  14307. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14308. }
  14309. else {
  14310. minFilter = gl.LINEAR;
  14311. }
  14312. break;
  14313. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14314. magFilter = gl.NEAREST;
  14315. if (generateMipMaps) {
  14316. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14317. }
  14318. else {
  14319. minFilter = gl.NEAREST;
  14320. }
  14321. break;
  14322. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14323. magFilter = gl.NEAREST;
  14324. if (generateMipMaps) {
  14325. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14326. }
  14327. else {
  14328. minFilter = gl.NEAREST;
  14329. }
  14330. break;
  14331. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14332. magFilter = gl.NEAREST;
  14333. if (generateMipMaps) {
  14334. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14335. }
  14336. else {
  14337. minFilter = gl.LINEAR;
  14338. }
  14339. break;
  14340. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14341. magFilter = gl.NEAREST;
  14342. if (generateMipMaps) {
  14343. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14344. }
  14345. else {
  14346. minFilter = gl.LINEAR;
  14347. }
  14348. break;
  14349. case Engine.TEXTURE_NEAREST_LINEAR:
  14350. magFilter = gl.NEAREST;
  14351. minFilter = gl.LINEAR;
  14352. break;
  14353. case Engine.TEXTURE_NEAREST_NEAREST:
  14354. magFilter = gl.NEAREST;
  14355. minFilter = gl.NEAREST;
  14356. break;
  14357. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14358. magFilter = gl.LINEAR;
  14359. if (generateMipMaps) {
  14360. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14361. }
  14362. else {
  14363. minFilter = gl.NEAREST;
  14364. }
  14365. break;
  14366. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14367. magFilter = gl.LINEAR;
  14368. if (generateMipMaps) {
  14369. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14370. }
  14371. else {
  14372. minFilter = gl.NEAREST;
  14373. }
  14374. break;
  14375. case Engine.TEXTURE_LINEAR_LINEAR:
  14376. magFilter = gl.LINEAR;
  14377. minFilter = gl.LINEAR;
  14378. break;
  14379. case Engine.TEXTURE_LINEAR_NEAREST:
  14380. magFilter = gl.LINEAR;
  14381. minFilter = gl.NEAREST;
  14382. break;
  14383. }
  14384. return {
  14385. min: minFilter,
  14386. mag: magFilter
  14387. };
  14388. };
  14389. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14390. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14391. var img;
  14392. var onload = function () {
  14393. loadedImages[index] = img;
  14394. loadedImages._internalCount++;
  14395. if (scene) {
  14396. scene._removePendingData(img);
  14397. }
  14398. if (loadedImages._internalCount === 6) {
  14399. onfinish(loadedImages);
  14400. }
  14401. };
  14402. var onerror = function (message, exception) {
  14403. if (scene) {
  14404. scene._removePendingData(img);
  14405. }
  14406. if (onErrorCallBack) {
  14407. onErrorCallBack(message, exception);
  14408. }
  14409. };
  14410. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14411. if (scene) {
  14412. scene._addPendingData(img);
  14413. }
  14414. };
  14415. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14416. if (onError === void 0) { onError = null; }
  14417. var loadedImages = [];
  14418. loadedImages._internalCount = 0;
  14419. for (var index = 0; index < 6; index++) {
  14420. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14421. }
  14422. };
  14423. ;
  14424. /** @hidden */
  14425. Engine.prototype._createTexture = function () {
  14426. var texture = this._gl.createTexture();
  14427. if (!texture) {
  14428. throw new Error("Unable to create texture");
  14429. }
  14430. return texture;
  14431. };
  14432. /**
  14433. * Usually called from BABYLON.Texture.ts.
  14434. * Passed information to create a WebGLTexture
  14435. * @param urlArg defines a value which contains one of the following:
  14436. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14437. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14438. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14439. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14440. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14441. * @param scene needed for loading to the correct scene
  14442. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14443. * @param onLoad optional callback to be called upon successful completion
  14444. * @param onError optional callback to be called upon failure
  14445. * @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
  14446. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14447. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14448. * @param forcedExtension defines the extension to use to pick the right loader
  14449. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14450. */
  14451. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14452. var _this = this;
  14453. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14454. if (onLoad === void 0) { onLoad = null; }
  14455. if (onError === void 0) { onError = null; }
  14456. if (buffer === void 0) { buffer = null; }
  14457. if (fallback === void 0) { fallback = null; }
  14458. if (format === void 0) { format = null; }
  14459. if (forcedExtension === void 0) { forcedExtension = null; }
  14460. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14461. var fromData = url.substr(0, 5) === "data:";
  14462. var fromBlob = url.substr(0, 5) === "blob:";
  14463. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14464. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14465. // establish the file extension, if possible
  14466. var lastDot = url.lastIndexOf('.');
  14467. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14468. var loader = null;
  14469. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14470. var availableLoader = _a[_i];
  14471. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14472. loader = availableLoader;
  14473. break;
  14474. }
  14475. }
  14476. if (loader) {
  14477. url = loader.transformUrl(url, this._textureFormatInUse);
  14478. }
  14479. if (scene) {
  14480. scene._addPendingData(texture);
  14481. }
  14482. texture.url = url;
  14483. texture.generateMipMaps = !noMipmap;
  14484. texture.samplingMode = samplingMode;
  14485. texture.invertY = invertY;
  14486. if (!this._doNotHandleContextLost) {
  14487. // Keep a link to the buffer only if we plan to handle context lost
  14488. texture._buffer = buffer;
  14489. }
  14490. var onLoadObserver = null;
  14491. if (onLoad && !fallback) {
  14492. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14493. }
  14494. if (!fallback)
  14495. this._internalTexturesCache.push(texture);
  14496. var onInternalError = function (message, exception) {
  14497. if (scene) {
  14498. scene._removePendingData(texture);
  14499. }
  14500. var customFallback = false;
  14501. if (loader) {
  14502. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14503. if (fallbackUrl) {
  14504. // Add Back
  14505. customFallback = true;
  14506. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14507. }
  14508. }
  14509. if (!customFallback) {
  14510. if (onLoadObserver) {
  14511. texture.onLoadedObservable.remove(onLoadObserver);
  14512. }
  14513. if (BABYLON.Tools.UseFallbackTexture) {
  14514. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14515. }
  14516. }
  14517. if (onError) {
  14518. onError(message || "Unknown error", exception);
  14519. }
  14520. };
  14521. // processing for non-image formats
  14522. if (loader) {
  14523. var callback = function (data) {
  14524. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14525. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14526. done();
  14527. return false;
  14528. }, samplingMode);
  14529. });
  14530. };
  14531. if (!buffer) {
  14532. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14533. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14534. });
  14535. }
  14536. else {
  14537. callback(buffer);
  14538. }
  14539. }
  14540. else {
  14541. var onload = function (img) {
  14542. if (fromBlob && !_this._doNotHandleContextLost) {
  14543. // We need to store the image if we need to rebuild the texture
  14544. // in case of a webgl context lost
  14545. texture._buffer = img;
  14546. }
  14547. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14548. var gl = _this._gl;
  14549. var isPot = (img.width === potWidth && img.height === potHeight);
  14550. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14551. if (isPot) {
  14552. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14553. return false;
  14554. }
  14555. var maxTextureSize = _this._caps.maxTextureSize;
  14556. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14557. _this._prepareWorkingCanvas();
  14558. if (!_this._workingCanvas || !_this._workingContext) {
  14559. return false;
  14560. }
  14561. _this._workingCanvas.width = potWidth;
  14562. _this._workingCanvas.height = potHeight;
  14563. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14564. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14565. texture.width = potWidth;
  14566. texture.height = potHeight;
  14567. return false;
  14568. }
  14569. else {
  14570. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14571. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14572. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14573. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14574. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14575. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14576. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14577. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14578. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14579. _this._releaseTexture(source_1);
  14580. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14581. continuationCallback();
  14582. });
  14583. }
  14584. return true;
  14585. }, samplingMode);
  14586. };
  14587. if (!fromData || isBase64) {
  14588. if (buffer instanceof HTMLImageElement) {
  14589. onload(buffer);
  14590. }
  14591. else {
  14592. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14593. }
  14594. }
  14595. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14596. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14597. }
  14598. else {
  14599. onload(buffer);
  14600. }
  14601. }
  14602. return texture;
  14603. };
  14604. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14605. var _this = this;
  14606. var rtt = this.createRenderTargetTexture({
  14607. width: destination.width,
  14608. height: destination.height,
  14609. }, {
  14610. generateMipMaps: false,
  14611. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14612. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14613. generateDepthBuffer: false,
  14614. generateStencilBuffer: false
  14615. });
  14616. if (!this._rescalePostProcess) {
  14617. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14618. }
  14619. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14620. _this._rescalePostProcess.onApply = function (effect) {
  14621. effect._bindTexture("textureSampler", source);
  14622. };
  14623. var hostingScene = scene;
  14624. if (!hostingScene) {
  14625. hostingScene = _this.scenes[_this.scenes.length - 1];
  14626. }
  14627. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14628. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14629. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14630. _this.unBindFramebuffer(rtt);
  14631. _this._releaseTexture(rtt);
  14632. if (onComplete) {
  14633. onComplete();
  14634. }
  14635. });
  14636. };
  14637. /**
  14638. * Update a raw texture
  14639. * @param texture defines the texture to update
  14640. * @param data defines the data to store in the texture
  14641. * @param format defines the format of the data
  14642. * @param invertY defines if data must be stored with Y axis inverted
  14643. * @param compression defines the compression used (null by default)
  14644. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14645. */
  14646. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14647. if (compression === void 0) { compression = null; }
  14648. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14649. if (!texture) {
  14650. return;
  14651. }
  14652. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14653. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14654. // babylon's internalFormat but gl's texImage2D format
  14655. var internalFormat = this._getInternalFormat(format);
  14656. var textureType = this._getWebGLTextureType(type);
  14657. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14658. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14659. if (!this._doNotHandleContextLost) {
  14660. texture._bufferView = data;
  14661. texture.format = format;
  14662. texture.type = type;
  14663. texture.invertY = invertY;
  14664. texture._compression = compression;
  14665. }
  14666. if (texture.width % 4 !== 0) {
  14667. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14668. }
  14669. if (compression && data) {
  14670. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14671. }
  14672. else {
  14673. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14674. }
  14675. if (texture.generateMipMaps) {
  14676. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14677. }
  14678. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14679. // this.resetTextureCache();
  14680. texture.isReady = true;
  14681. };
  14682. /**
  14683. * Creates a raw texture
  14684. * @param data defines the data to store in the texture
  14685. * @param width defines the width of the texture
  14686. * @param height defines the height of the texture
  14687. * @param format defines the format of the data
  14688. * @param generateMipMaps defines if the engine should generate the mip levels
  14689. * @param invertY defines if data must be stored with Y axis inverted
  14690. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14691. * @param compression defines the compression used (null by default)
  14692. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14693. * @returns the raw texture inside an InternalTexture
  14694. */
  14695. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14696. if (compression === void 0) { compression = null; }
  14697. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14698. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14699. texture.baseWidth = width;
  14700. texture.baseHeight = height;
  14701. texture.width = width;
  14702. texture.height = height;
  14703. texture.format = format;
  14704. texture.generateMipMaps = generateMipMaps;
  14705. texture.samplingMode = samplingMode;
  14706. texture.invertY = invertY;
  14707. texture._compression = compression;
  14708. texture.type = type;
  14709. if (!this._doNotHandleContextLost) {
  14710. texture._bufferView = data;
  14711. }
  14712. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14713. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14714. // Filters
  14715. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14716. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14717. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14718. if (generateMipMaps) {
  14719. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14720. }
  14721. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14722. this._internalTexturesCache.push(texture);
  14723. return texture;
  14724. };
  14725. /** @hidden */
  14726. Engine.prototype._unpackFlipY = function (value) {
  14727. if (this._unpackFlipYCached !== value) {
  14728. this._unpackFlipYCached = value;
  14729. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14730. }
  14731. };
  14732. /** @hidden */
  14733. Engine.prototype._getUnpackAlignement = function () {
  14734. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14735. };
  14736. /**
  14737. * Creates a dynamic texture
  14738. * @param width defines the width of the texture
  14739. * @param height defines the height of the texture
  14740. * @param generateMipMaps defines if the engine should generate the mip levels
  14741. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14742. * @returns the dynamic texture inside an InternalTexture
  14743. */
  14744. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14745. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14746. texture.baseWidth = width;
  14747. texture.baseHeight = height;
  14748. if (generateMipMaps) {
  14749. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14750. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14751. }
  14752. // this.resetTextureCache();
  14753. texture.width = width;
  14754. texture.height = height;
  14755. texture.isReady = false;
  14756. texture.generateMipMaps = generateMipMaps;
  14757. texture.samplingMode = samplingMode;
  14758. this.updateTextureSamplingMode(samplingMode, texture);
  14759. this._internalTexturesCache.push(texture);
  14760. return texture;
  14761. };
  14762. /**
  14763. * Update the sampling mode of a given texture
  14764. * @param samplingMode defines the required sampling mode
  14765. * @param texture defines the texture to update
  14766. */
  14767. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14768. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14769. if (texture.isCube) {
  14770. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14771. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14772. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14773. }
  14774. else if (texture.is3D) {
  14775. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14776. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14777. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14778. }
  14779. else {
  14780. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14781. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14782. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14783. }
  14784. texture.samplingMode = samplingMode;
  14785. };
  14786. /**
  14787. * Update the content of a dynamic texture
  14788. * @param texture defines the texture to update
  14789. * @param canvas defines the canvas containing the source
  14790. * @param invertY defines if data must be stored with Y axis inverted
  14791. * @param premulAlpha defines if alpha is stored as premultiplied
  14792. * @param format defines the format of the data
  14793. */
  14794. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14795. if (premulAlpha === void 0) { premulAlpha = false; }
  14796. if (!texture) {
  14797. return;
  14798. }
  14799. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14800. this._unpackFlipY(invertY);
  14801. if (premulAlpha) {
  14802. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14803. }
  14804. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14805. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14806. if (texture.generateMipMaps) {
  14807. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14808. }
  14809. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14810. if (premulAlpha) {
  14811. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14812. }
  14813. texture.isReady = true;
  14814. };
  14815. /**
  14816. * Update a video texture
  14817. * @param texture defines the texture to update
  14818. * @param video defines the video element to use
  14819. * @param invertY defines if data must be stored with Y axis inverted
  14820. */
  14821. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14822. if (!texture || texture._isDisabled) {
  14823. return;
  14824. }
  14825. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14826. this._unpackFlipY(!invertY); // Video are upside down by default
  14827. try {
  14828. // Testing video texture support
  14829. if (this._videoTextureSupported === undefined) {
  14830. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14831. if (this._gl.getError() !== 0) {
  14832. this._videoTextureSupported = false;
  14833. }
  14834. else {
  14835. this._videoTextureSupported = true;
  14836. }
  14837. }
  14838. // Copy video through the current working canvas if video texture is not supported
  14839. if (!this._videoTextureSupported) {
  14840. if (!texture._workingCanvas) {
  14841. texture._workingCanvas = document.createElement("canvas");
  14842. var context = texture._workingCanvas.getContext("2d");
  14843. if (!context) {
  14844. throw new Error("Unable to get 2d context");
  14845. }
  14846. texture._workingContext = context;
  14847. texture._workingCanvas.width = texture.width;
  14848. texture._workingCanvas.height = texture.height;
  14849. }
  14850. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14851. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14852. }
  14853. else {
  14854. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14855. }
  14856. if (texture.generateMipMaps) {
  14857. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14858. }
  14859. if (!wasPreviouslyBound) {
  14860. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14861. }
  14862. // this.resetTextureCache();
  14863. texture.isReady = true;
  14864. }
  14865. catch (ex) {
  14866. // Something unexpected
  14867. // Let's disable the texture
  14868. texture._isDisabled = true;
  14869. }
  14870. };
  14871. /**
  14872. * Updates a depth texture Comparison Mode and Function.
  14873. * If the comparison Function is equal to 0, the mode will be set to none.
  14874. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14875. * @param texture The texture to set the comparison function for
  14876. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14877. */
  14878. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14879. if (this.webGLVersion === 1) {
  14880. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14881. return;
  14882. }
  14883. var gl = this._gl;
  14884. if (texture.isCube) {
  14885. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14886. if (comparisonFunction === 0) {
  14887. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14888. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14889. }
  14890. else {
  14891. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14892. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14893. }
  14894. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14895. }
  14896. else {
  14897. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14898. if (comparisonFunction === 0) {
  14899. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14900. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14901. }
  14902. else {
  14903. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14904. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14905. }
  14906. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14907. }
  14908. texture._comparisonFunction = comparisonFunction;
  14909. };
  14910. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14911. var width = size.width || size;
  14912. var height = size.height || size;
  14913. internalTexture.baseWidth = width;
  14914. internalTexture.baseHeight = height;
  14915. internalTexture.width = width;
  14916. internalTexture.height = height;
  14917. internalTexture.isReady = true;
  14918. internalTexture.samples = 1;
  14919. internalTexture.generateMipMaps = false;
  14920. internalTexture._generateDepthBuffer = true;
  14921. internalTexture._generateStencilBuffer = generateStencil;
  14922. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14923. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14924. internalTexture._comparisonFunction = comparisonFunction;
  14925. var gl = this._gl;
  14926. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14927. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  14928. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14929. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14930. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14931. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14932. if (comparisonFunction === 0) {
  14933. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14934. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14935. }
  14936. else {
  14937. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14938. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14939. }
  14940. };
  14941. /**
  14942. * Creates a depth stencil texture.
  14943. * This is only available in WebGL 2 or with the depth texture extension available.
  14944. * @param size The size of face edge in the texture.
  14945. * @param options The options defining the texture.
  14946. * @returns The texture
  14947. */
  14948. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14949. if (options.isCube) {
  14950. var width = size.width || size;
  14951. return this._createDepthStencilCubeTexture(width, options);
  14952. }
  14953. else {
  14954. return this._createDepthStencilTexture(size, options);
  14955. }
  14956. };
  14957. /**
  14958. * Creates a depth stencil texture.
  14959. * This is only available in WebGL 2 or with the depth texture extension available.
  14960. * @param size The size of face edge in the texture.
  14961. * @param options The options defining the texture.
  14962. * @returns The texture
  14963. */
  14964. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14965. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14966. if (!this._caps.depthTextureExtension) {
  14967. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14968. return internalTexture;
  14969. }
  14970. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14971. var gl = this._gl;
  14972. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14973. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14974. if (this.webGLVersion > 1) {
  14975. if (internalOptions.generateStencil) {
  14976. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14977. }
  14978. else {
  14979. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14980. }
  14981. }
  14982. else {
  14983. if (internalOptions.generateStencil) {
  14984. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14985. }
  14986. else {
  14987. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14988. }
  14989. }
  14990. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14991. return internalTexture;
  14992. };
  14993. /**
  14994. * Creates a depth stencil cube texture.
  14995. * This is only available in WebGL 2.
  14996. * @param size The size of face edge in the cube texture.
  14997. * @param options The options defining the cube texture.
  14998. * @returns The cube texture
  14999. */
  15000. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15001. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15002. internalTexture.isCube = true;
  15003. if (this.webGLVersion === 1) {
  15004. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15005. return internalTexture;
  15006. }
  15007. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15008. var gl = this._gl;
  15009. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15010. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15011. // Create the depth/stencil buffer
  15012. for (var face = 0; face < 6; face++) {
  15013. if (internalOptions.generateStencil) {
  15014. 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);
  15015. }
  15016. else {
  15017. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15018. }
  15019. }
  15020. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15021. return internalTexture;
  15022. };
  15023. /**
  15024. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15025. * @param renderTarget The render target to set the frame buffer for
  15026. */
  15027. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15028. // Create the framebuffer
  15029. var internalTexture = renderTarget.getInternalTexture();
  15030. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15031. return;
  15032. }
  15033. var gl = this._gl;
  15034. var depthStencilTexture = renderTarget.depthStencilTexture;
  15035. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15036. if (depthStencilTexture.isCube) {
  15037. if (depthStencilTexture._generateStencilBuffer) {
  15038. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15039. }
  15040. else {
  15041. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15042. }
  15043. }
  15044. else {
  15045. if (depthStencilTexture._generateStencilBuffer) {
  15046. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15047. }
  15048. else {
  15049. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15050. }
  15051. }
  15052. this.bindUnboundFramebuffer(null);
  15053. };
  15054. /**
  15055. * Creates a new render target texture
  15056. * @param size defines the size of the texture
  15057. * @param options defines the options used to create the texture
  15058. * @returns a new render target texture stored in an InternalTexture
  15059. */
  15060. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15061. var fullOptions = new RenderTargetCreationOptions();
  15062. if (options !== undefined && typeof options === "object") {
  15063. fullOptions.generateMipMaps = options.generateMipMaps;
  15064. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15065. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15066. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15067. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15068. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15069. }
  15070. else {
  15071. fullOptions.generateMipMaps = options;
  15072. fullOptions.generateDepthBuffer = true;
  15073. fullOptions.generateStencilBuffer = false;
  15074. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15075. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15076. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15077. }
  15078. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15079. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15080. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15081. }
  15082. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15083. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15084. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15085. }
  15086. var gl = this._gl;
  15087. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15088. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15089. var width = size.width || size;
  15090. var height = size.height || size;
  15091. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15092. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15093. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15094. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15095. }
  15096. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15097. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15098. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15099. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15100. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15101. // Create the framebuffer
  15102. var currentFrameBuffer = this._currentFramebuffer;
  15103. var framebuffer = gl.createFramebuffer();
  15104. this.bindUnboundFramebuffer(framebuffer);
  15105. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15106. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15107. if (fullOptions.generateMipMaps) {
  15108. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15109. }
  15110. // Unbind
  15111. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15112. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15113. this.bindUnboundFramebuffer(currentFrameBuffer);
  15114. texture._framebuffer = framebuffer;
  15115. texture.baseWidth = width;
  15116. texture.baseHeight = height;
  15117. texture.width = width;
  15118. texture.height = height;
  15119. texture.isReady = true;
  15120. texture.samples = 1;
  15121. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15122. texture.samplingMode = fullOptions.samplingMode;
  15123. texture.type = fullOptions.type;
  15124. texture.format = fullOptions.format;
  15125. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15126. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15127. // this.resetTextureCache();
  15128. this._internalTexturesCache.push(texture);
  15129. return texture;
  15130. };
  15131. /**
  15132. * Create a multi render target texture
  15133. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15134. * @param size defines the size of the texture
  15135. * @param options defines the creation options
  15136. * @returns the cube texture as an InternalTexture
  15137. */
  15138. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15139. var generateMipMaps = false;
  15140. var generateDepthBuffer = true;
  15141. var generateStencilBuffer = false;
  15142. var generateDepthTexture = false;
  15143. var textureCount = 1;
  15144. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15145. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15146. var types = new Array();
  15147. var samplingModes = new Array();
  15148. if (options !== undefined) {
  15149. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15150. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15151. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15152. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15153. textureCount = options.textureCount || 1;
  15154. if (options.types) {
  15155. types = options.types;
  15156. }
  15157. if (options.samplingModes) {
  15158. samplingModes = options.samplingModes;
  15159. }
  15160. }
  15161. var gl = this._gl;
  15162. // Create the framebuffer
  15163. var framebuffer = gl.createFramebuffer();
  15164. this.bindUnboundFramebuffer(framebuffer);
  15165. var width = size.width || size;
  15166. var height = size.height || size;
  15167. var textures = [];
  15168. var attachments = [];
  15169. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15170. for (var i = 0; i < textureCount; i++) {
  15171. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15172. var type = types[i] || defaultType;
  15173. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15174. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15175. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15176. }
  15177. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15178. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15179. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15180. }
  15181. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15182. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15183. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15184. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15185. }
  15186. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15187. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15188. textures.push(texture);
  15189. attachments.push(attachment);
  15190. gl.activeTexture(gl["TEXTURE" + i]);
  15191. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15192. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15193. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15194. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15195. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15196. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15197. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15198. if (generateMipMaps) {
  15199. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15200. }
  15201. // Unbind
  15202. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15203. texture._framebuffer = framebuffer;
  15204. texture._depthStencilBuffer = depthStencilBuffer;
  15205. texture.baseWidth = width;
  15206. texture.baseHeight = height;
  15207. texture.width = width;
  15208. texture.height = height;
  15209. texture.isReady = true;
  15210. texture.samples = 1;
  15211. texture.generateMipMaps = generateMipMaps;
  15212. texture.samplingMode = samplingMode;
  15213. texture.type = type;
  15214. texture._generateDepthBuffer = generateDepthBuffer;
  15215. texture._generateStencilBuffer = generateStencilBuffer;
  15216. texture._attachments = attachments;
  15217. this._internalTexturesCache.push(texture);
  15218. }
  15219. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15220. // Depth texture
  15221. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15222. gl.activeTexture(gl.TEXTURE0);
  15223. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15224. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15225. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15226. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15227. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15228. 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);
  15229. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15230. depthTexture._framebuffer = framebuffer;
  15231. depthTexture.baseWidth = width;
  15232. depthTexture.baseHeight = height;
  15233. depthTexture.width = width;
  15234. depthTexture.height = height;
  15235. depthTexture.isReady = true;
  15236. depthTexture.samples = 1;
  15237. depthTexture.generateMipMaps = generateMipMaps;
  15238. depthTexture.samplingMode = gl.NEAREST;
  15239. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15240. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15241. textures.push(depthTexture);
  15242. this._internalTexturesCache.push(depthTexture);
  15243. }
  15244. gl.drawBuffers(attachments);
  15245. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15246. this.bindUnboundFramebuffer(null);
  15247. this.resetTextureCache();
  15248. return textures;
  15249. };
  15250. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15251. if (samples === void 0) { samples = 1; }
  15252. var depthStencilBuffer = null;
  15253. var gl = this._gl;
  15254. // Create the depth/stencil buffer
  15255. if (generateStencilBuffer) {
  15256. depthStencilBuffer = gl.createRenderbuffer();
  15257. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15258. if (samples > 1) {
  15259. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15260. }
  15261. else {
  15262. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15263. }
  15264. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15265. }
  15266. else if (generateDepthBuffer) {
  15267. depthStencilBuffer = gl.createRenderbuffer();
  15268. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15269. if (samples > 1) {
  15270. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15271. }
  15272. else {
  15273. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15274. }
  15275. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15276. }
  15277. return depthStencilBuffer;
  15278. };
  15279. /**
  15280. * Updates the sample count of a render target texture
  15281. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15282. * @param texture defines the texture to update
  15283. * @param samples defines the sample count to set
  15284. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15285. */
  15286. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15287. if (this.webGLVersion < 2 || !texture) {
  15288. return 1;
  15289. }
  15290. if (texture.samples === samples) {
  15291. return samples;
  15292. }
  15293. var gl = this._gl;
  15294. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15295. // Dispose previous render buffers
  15296. if (texture._depthStencilBuffer) {
  15297. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15298. texture._depthStencilBuffer = null;
  15299. }
  15300. if (texture._MSAAFramebuffer) {
  15301. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15302. texture._MSAAFramebuffer = null;
  15303. }
  15304. if (texture._MSAARenderBuffer) {
  15305. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15306. texture._MSAARenderBuffer = null;
  15307. }
  15308. if (samples > 1) {
  15309. var framebuffer = gl.createFramebuffer();
  15310. if (!framebuffer) {
  15311. throw new Error("Unable to create multi sampled framebuffer");
  15312. }
  15313. texture._MSAAFramebuffer = framebuffer;
  15314. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15315. var colorRenderbuffer = gl.createRenderbuffer();
  15316. if (!colorRenderbuffer) {
  15317. throw new Error("Unable to create multi sampled framebuffer");
  15318. }
  15319. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15320. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15321. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15322. texture._MSAARenderBuffer = colorRenderbuffer;
  15323. }
  15324. else {
  15325. this.bindUnboundFramebuffer(texture._framebuffer);
  15326. }
  15327. texture.samples = samples;
  15328. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15329. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15330. this.bindUnboundFramebuffer(null);
  15331. return samples;
  15332. };
  15333. /**
  15334. * Update the sample count for a given multiple render target texture
  15335. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15336. * @param textures defines the textures to update
  15337. * @param samples defines the sample count to set
  15338. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15339. */
  15340. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15341. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15342. return 1;
  15343. }
  15344. if (textures[0].samples === samples) {
  15345. return samples;
  15346. }
  15347. var gl = this._gl;
  15348. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15349. // Dispose previous render buffers
  15350. if (textures[0]._depthStencilBuffer) {
  15351. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15352. textures[0]._depthStencilBuffer = null;
  15353. }
  15354. if (textures[0]._MSAAFramebuffer) {
  15355. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15356. textures[0]._MSAAFramebuffer = null;
  15357. }
  15358. for (var i = 0; i < textures.length; i++) {
  15359. if (textures[i]._MSAARenderBuffer) {
  15360. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15361. textures[i]._MSAARenderBuffer = null;
  15362. }
  15363. }
  15364. if (samples > 1) {
  15365. var framebuffer = gl.createFramebuffer();
  15366. if (!framebuffer) {
  15367. throw new Error("Unable to create multi sampled framebuffer");
  15368. }
  15369. this.bindUnboundFramebuffer(framebuffer);
  15370. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15371. var attachments = [];
  15372. for (var i = 0; i < textures.length; i++) {
  15373. var texture = textures[i];
  15374. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15375. var colorRenderbuffer = gl.createRenderbuffer();
  15376. if (!colorRenderbuffer) {
  15377. throw new Error("Unable to create multi sampled framebuffer");
  15378. }
  15379. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15380. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15381. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15382. texture._MSAAFramebuffer = framebuffer;
  15383. texture._MSAARenderBuffer = colorRenderbuffer;
  15384. texture.samples = samples;
  15385. texture._depthStencilBuffer = depthStencilBuffer;
  15386. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15387. attachments.push(attachment);
  15388. }
  15389. gl.drawBuffers(attachments);
  15390. }
  15391. else {
  15392. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15393. }
  15394. this.bindUnboundFramebuffer(null);
  15395. return samples;
  15396. };
  15397. /** @hidden */
  15398. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15399. if (faceIndex === void 0) { faceIndex = 0; }
  15400. if (lod === void 0) { lod = 0; }
  15401. var gl = this._gl;
  15402. var target = gl.TEXTURE_2D;
  15403. if (texture.isCube) {
  15404. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15405. }
  15406. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15407. };
  15408. /** @hidden */
  15409. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15410. if (faceIndex === void 0) { faceIndex = 0; }
  15411. if (lod === void 0) { lod = 0; }
  15412. var gl = this._gl;
  15413. var textureType = this._getWebGLTextureType(texture.type);
  15414. var format = this._getInternalFormat(texture.format);
  15415. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15416. this._unpackFlipY(texture.invertY);
  15417. var target = gl.TEXTURE_2D;
  15418. if (texture.isCube) {
  15419. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15420. }
  15421. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15422. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15423. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15424. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15425. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15426. };
  15427. /** @hidden */
  15428. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15429. if (faceIndex === void 0) { faceIndex = 0; }
  15430. if (lod === void 0) { lod = 0; }
  15431. var gl = this._gl;
  15432. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15433. this._bindTextureDirectly(bindTarget, texture, true);
  15434. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15435. this._bindTextureDirectly(bindTarget, null, true);
  15436. };
  15437. /** @hidden */
  15438. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15439. if (faceIndex === void 0) { faceIndex = 0; }
  15440. if (lod === void 0) { lod = 0; }
  15441. var gl = this._gl;
  15442. var textureType = this._getWebGLTextureType(texture.type);
  15443. var format = this._getInternalFormat(texture.format);
  15444. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15445. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15446. this._bindTextureDirectly(bindTarget, texture, true);
  15447. this._unpackFlipY(texture.invertY);
  15448. var target = gl.TEXTURE_2D;
  15449. if (texture.isCube) {
  15450. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15451. }
  15452. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15453. this._bindTextureDirectly(bindTarget, null, true);
  15454. };
  15455. /**
  15456. * Creates a new render target cube texture
  15457. * @param size defines the size of the texture
  15458. * @param options defines the options used to create the texture
  15459. * @returns a new render target cube texture stored in an InternalTexture
  15460. */
  15461. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15462. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15463. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15464. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15465. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15466. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15467. }
  15468. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15469. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15470. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15471. }
  15472. var gl = this._gl;
  15473. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15474. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15475. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15476. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15477. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15478. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15479. }
  15480. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15481. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15482. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15483. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15484. for (var face = 0; face < 6; face++) {
  15485. 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);
  15486. }
  15487. // Create the framebuffer
  15488. var framebuffer = gl.createFramebuffer();
  15489. this.bindUnboundFramebuffer(framebuffer);
  15490. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15491. // MipMaps
  15492. if (fullOptions.generateMipMaps) {
  15493. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15494. }
  15495. // Unbind
  15496. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15497. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15498. this.bindUnboundFramebuffer(null);
  15499. texture._framebuffer = framebuffer;
  15500. texture.width = size;
  15501. texture.height = size;
  15502. texture.isReady = true;
  15503. texture.isCube = true;
  15504. texture.samples = 1;
  15505. texture.generateMipMaps = fullOptions.generateMipMaps;
  15506. texture.samplingMode = fullOptions.samplingMode;
  15507. texture.type = fullOptions.type;
  15508. texture.format = fullOptions.format;
  15509. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15510. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15511. this._internalTexturesCache.push(texture);
  15512. return texture;
  15513. };
  15514. /**
  15515. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15516. * @param rootUrl defines the url where the file to load is located
  15517. * @param scene defines the current scene
  15518. * @param lodScale defines scale to apply to the mip map selection
  15519. * @param lodOffset defines offset to apply to the mip map selection
  15520. * @param onLoad defines an optional callback raised when the texture is loaded
  15521. * @param onError defines an optional callback raised if there is an issue to load the texture
  15522. * @param format defines the format of the data
  15523. * @param forcedExtension defines the extension to use to pick the right loader
  15524. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15525. * @returns the cube texture as an InternalTexture
  15526. */
  15527. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15528. var _this = this;
  15529. if (onLoad === void 0) { onLoad = null; }
  15530. if (onError === void 0) { onError = null; }
  15531. if (forcedExtension === void 0) { forcedExtension = null; }
  15532. if (createPolynomials === void 0) { createPolynomials = true; }
  15533. var callback = function (loadData) {
  15534. if (!loadData) {
  15535. if (onLoad) {
  15536. onLoad(null);
  15537. }
  15538. return;
  15539. }
  15540. var texture = loadData.texture;
  15541. if (!createPolynomials) {
  15542. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15543. }
  15544. else if (loadData.info.sphericalPolynomial) {
  15545. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15546. }
  15547. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15548. if (_this._caps.textureLOD) {
  15549. // Do not add extra process if texture lod is supported.
  15550. if (onLoad) {
  15551. onLoad(texture);
  15552. }
  15553. return;
  15554. }
  15555. var mipSlices = 3;
  15556. var gl = _this._gl;
  15557. var width = loadData.width;
  15558. if (!width) {
  15559. return;
  15560. }
  15561. var textures = [];
  15562. for (var i = 0; i < mipSlices; i++) {
  15563. //compute LOD from even spacing in smoothness (matching shader calculation)
  15564. var smoothness = i / (mipSlices - 1);
  15565. var roughness = 1 - smoothness;
  15566. var minLODIndex = lodOffset; // roughness = 0
  15567. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15568. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15569. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15570. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15571. glTextureFromLod.type = texture.type;
  15572. glTextureFromLod.format = texture.format;
  15573. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15574. glTextureFromLod.height = glTextureFromLod.width;
  15575. glTextureFromLod.isCube = true;
  15576. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15577. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15578. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15579. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15580. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15581. if (loadData.isDDS) {
  15582. var info = loadData.info;
  15583. var data = loadData.data;
  15584. _this._unpackFlipY(info.isCompressed);
  15585. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15586. }
  15587. else {
  15588. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15589. }
  15590. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15591. // Wrap in a base texture for easy binding.
  15592. var lodTexture = new BABYLON.BaseTexture(scene);
  15593. lodTexture.isCube = true;
  15594. lodTexture._texture = glTextureFromLod;
  15595. glTextureFromLod.isReady = true;
  15596. textures.push(lodTexture);
  15597. }
  15598. texture._lodTextureHigh = textures[2];
  15599. texture._lodTextureMid = textures[1];
  15600. texture._lodTextureLow = textures[0];
  15601. if (onLoad) {
  15602. onLoad(texture);
  15603. }
  15604. };
  15605. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15606. };
  15607. /**
  15608. * Creates a cube texture
  15609. * @param rootUrl defines the url where the files to load is located
  15610. * @param scene defines the current scene
  15611. * @param files defines the list of files to load (1 per face)
  15612. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15613. * @param onLoad defines an optional callback raised when the texture is loaded
  15614. * @param onError defines an optional callback raised if there is an issue to load the texture
  15615. * @param format defines the format of the data
  15616. * @param forcedExtension defines the extension to use to pick the right loader
  15617. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15618. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15619. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15620. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15621. * @returns the cube texture as an InternalTexture
  15622. */
  15623. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15624. var _this = this;
  15625. if (onLoad === void 0) { onLoad = null; }
  15626. if (onError === void 0) { onError = null; }
  15627. if (forcedExtension === void 0) { forcedExtension = null; }
  15628. if (createPolynomials === void 0) { createPolynomials = false; }
  15629. if (lodScale === void 0) { lodScale = 0; }
  15630. if (lodOffset === void 0) { lodOffset = 0; }
  15631. if (fallback === void 0) { fallback = null; }
  15632. var gl = this._gl;
  15633. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15634. texture.isCube = true;
  15635. texture.url = rootUrl;
  15636. texture.generateMipMaps = !noMipmap;
  15637. texture._lodGenerationScale = lodScale;
  15638. texture._lodGenerationOffset = lodOffset;
  15639. if (!this._doNotHandleContextLost) {
  15640. texture._extension = forcedExtension;
  15641. texture._files = files;
  15642. }
  15643. var lastDot = rootUrl.lastIndexOf('.');
  15644. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15645. var loader = null;
  15646. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15647. var availableLoader = _a[_i];
  15648. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15649. loader = availableLoader;
  15650. break;
  15651. }
  15652. }
  15653. var onInternalError = function (request, exception) {
  15654. if (loader) {
  15655. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15656. if (fallbackUrl) {
  15657. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15658. }
  15659. }
  15660. if (onError && request) {
  15661. onError(request.status + " " + request.statusText, exception);
  15662. }
  15663. };
  15664. if (loader) {
  15665. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15666. var onloaddata = function (data) {
  15667. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15668. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15669. };
  15670. if (files && files.length === 6) {
  15671. if (loader.supportCascades) {
  15672. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15673. }
  15674. else if (onError) {
  15675. onError("Textures type does not support cascades.");
  15676. }
  15677. }
  15678. else {
  15679. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15680. }
  15681. }
  15682. else {
  15683. if (!files) {
  15684. throw new Error("Cannot load cubemap because files were not defined");
  15685. }
  15686. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15687. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15688. var height = width;
  15689. _this._prepareWorkingCanvas();
  15690. if (!_this._workingCanvas || !_this._workingContext) {
  15691. return;
  15692. }
  15693. _this._workingCanvas.width = width;
  15694. _this._workingCanvas.height = height;
  15695. var faces = [
  15696. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15697. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15698. ];
  15699. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15700. _this._unpackFlipY(false);
  15701. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15702. for (var index = 0; index < faces.length; index++) {
  15703. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15704. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15705. }
  15706. if (!noMipmap) {
  15707. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15708. }
  15709. _this._setCubeMapTextureParams(!noMipmap);
  15710. texture.width = width;
  15711. texture.height = height;
  15712. texture.isReady = true;
  15713. if (format) {
  15714. texture.format = format;
  15715. }
  15716. texture.onLoadedObservable.notifyObservers(texture);
  15717. texture.onLoadedObservable.clear();
  15718. if (onLoad) {
  15719. onLoad();
  15720. }
  15721. }, files, onError);
  15722. }
  15723. this._internalTexturesCache.push(texture);
  15724. return texture;
  15725. };
  15726. /**
  15727. * @hidden
  15728. */
  15729. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15730. var gl = this._gl;
  15731. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15732. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15733. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15734. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15735. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15736. // this.resetTextureCache();
  15737. };
  15738. /**
  15739. * Update a raw cube texture
  15740. * @param texture defines the texture to udpdate
  15741. * @param data defines the data to store
  15742. * @param format defines the data format
  15743. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15744. * @param invertY defines if data must be stored with Y axis inverted
  15745. * @param compression defines the compression used (null by default)
  15746. * @param level defines which level of the texture to update
  15747. */
  15748. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15749. if (compression === void 0) { compression = null; }
  15750. if (level === void 0) { level = 0; }
  15751. texture._bufferViewArray = data;
  15752. texture.format = format;
  15753. texture.type = type;
  15754. texture.invertY = invertY;
  15755. texture._compression = compression;
  15756. var gl = this._gl;
  15757. var textureType = this._getWebGLTextureType(type);
  15758. var internalFormat = this._getInternalFormat(format);
  15759. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15760. var needConversion = false;
  15761. if (internalFormat === gl.RGB) {
  15762. internalFormat = gl.RGBA;
  15763. needConversion = true;
  15764. }
  15765. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15766. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15767. if (texture.width % 4 !== 0) {
  15768. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15769. }
  15770. // Data are known to be in +X +Y +Z -X -Y -Z
  15771. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15772. var faceData = data[faceIndex];
  15773. if (compression) {
  15774. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15775. }
  15776. else {
  15777. if (needConversion) {
  15778. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15779. }
  15780. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15781. }
  15782. }
  15783. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15784. if (isPot && texture.generateMipMaps && level === 0) {
  15785. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15786. }
  15787. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15788. // this.resetTextureCache();
  15789. texture.isReady = true;
  15790. };
  15791. /**
  15792. * Creates a new raw cube texture
  15793. * @param data defines the array of data to use to create each face
  15794. * @param size defines the size of the textures
  15795. * @param format defines the format of the data
  15796. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15797. * @param generateMipMaps defines if the engine should generate the mip levels
  15798. * @param invertY defines if data must be stored with Y axis inverted
  15799. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15800. * @param compression defines the compression used (null by default)
  15801. * @returns the cube texture as an InternalTexture
  15802. */
  15803. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15804. if (compression === void 0) { compression = null; }
  15805. var gl = this._gl;
  15806. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15807. texture.isCube = true;
  15808. texture.format = format;
  15809. texture.type = type;
  15810. if (!this._doNotHandleContextLost) {
  15811. texture._bufferViewArray = data;
  15812. }
  15813. var textureType = this._getWebGLTextureType(type);
  15814. var internalFormat = this._getInternalFormat(format);
  15815. if (internalFormat === gl.RGB) {
  15816. internalFormat = gl.RGBA;
  15817. }
  15818. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15819. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15820. generateMipMaps = false;
  15821. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15822. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15823. }
  15824. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15825. generateMipMaps = false;
  15826. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15827. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15828. }
  15829. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15830. generateMipMaps = false;
  15831. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15832. }
  15833. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15834. generateMipMaps = false;
  15835. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15836. }
  15837. var width = size;
  15838. var height = width;
  15839. texture.width = width;
  15840. texture.height = height;
  15841. // Double check on POT to generate Mips.
  15842. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15843. if (!isPot) {
  15844. generateMipMaps = false;
  15845. }
  15846. // Upload data if needed. The texture won't be ready until then.
  15847. if (data) {
  15848. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15849. }
  15850. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15851. // Filters
  15852. if (data && generateMipMaps) {
  15853. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15854. }
  15855. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15856. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15857. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15858. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15859. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15860. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15861. texture.generateMipMaps = generateMipMaps;
  15862. return texture;
  15863. };
  15864. /**
  15865. * Creates a new raw cube texture from a specified url
  15866. * @param url defines the url where the data is located
  15867. * @param scene defines the current scene
  15868. * @param size defines the size of the textures
  15869. * @param format defines the format of the data
  15870. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15871. * @param noMipmap defines if the engine should avoid generating the mip levels
  15872. * @param callback defines a callback used to extract texture data from loaded data
  15873. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15874. * @param onLoad defines a callback called when texture is loaded
  15875. * @param onError defines a callback called if there is an error
  15876. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15877. * @param invertY defines if data must be stored with Y axis inverted
  15878. * @returns the cube texture as an InternalTexture
  15879. */
  15880. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15881. var _this = this;
  15882. if (onLoad === void 0) { onLoad = null; }
  15883. if (onError === void 0) { onError = null; }
  15884. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15885. if (invertY === void 0) { invertY = false; }
  15886. var gl = this._gl;
  15887. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15888. scene._addPendingData(texture);
  15889. texture.url = url;
  15890. this._internalTexturesCache.push(texture);
  15891. var onerror = function (request, exception) {
  15892. scene._removePendingData(texture);
  15893. if (onError && request) {
  15894. onError(request.status + " " + request.statusText, exception);
  15895. }
  15896. };
  15897. var internalCallback = function (data) {
  15898. var width = texture.width;
  15899. var faceDataArrays = callback(data);
  15900. if (!faceDataArrays) {
  15901. return;
  15902. }
  15903. if (mipmapGenerator) {
  15904. var textureType = _this._getWebGLTextureType(type);
  15905. var internalFormat = _this._getInternalFormat(format);
  15906. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15907. var needConversion = false;
  15908. if (internalFormat === gl.RGB) {
  15909. internalFormat = gl.RGBA;
  15910. needConversion = true;
  15911. }
  15912. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15913. _this._unpackFlipY(false);
  15914. var mipData = mipmapGenerator(faceDataArrays);
  15915. for (var level = 0; level < mipData.length; level++) {
  15916. var mipSize = width >> level;
  15917. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15918. var mipFaceData = mipData[level][faceIndex];
  15919. if (needConversion) {
  15920. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15921. }
  15922. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15923. }
  15924. }
  15925. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15926. }
  15927. else {
  15928. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15929. }
  15930. texture.isReady = true;
  15931. // this.resetTextureCache();
  15932. scene._removePendingData(texture);
  15933. if (onLoad) {
  15934. onLoad();
  15935. }
  15936. };
  15937. this._loadFile(url, function (data) {
  15938. internalCallback(data);
  15939. }, undefined, scene.database, true, onerror);
  15940. return texture;
  15941. };
  15942. ;
  15943. /**
  15944. * Update a raw 3D texture
  15945. * @param texture defines the texture to update
  15946. * @param data defines the data to store
  15947. * @param format defines the data format
  15948. * @param invertY defines if data must be stored with Y axis inverted
  15949. * @param compression defines the used compression (can be null)
  15950. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15951. */
  15952. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  15953. if (compression === void 0) { compression = null; }
  15954. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15955. var internalType = this._getWebGLTextureType(textureType);
  15956. var internalFormat = this._getInternalFormat(format);
  15957. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  15958. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15959. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15960. if (!this._doNotHandleContextLost) {
  15961. texture._bufferView = data;
  15962. texture.format = format;
  15963. texture.invertY = invertY;
  15964. texture._compression = compression;
  15965. }
  15966. if (texture.width % 4 !== 0) {
  15967. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15968. }
  15969. if (compression && data) {
  15970. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15971. }
  15972. else {
  15973. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  15974. }
  15975. if (texture.generateMipMaps) {
  15976. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15977. }
  15978. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15979. // this.resetTextureCache();
  15980. texture.isReady = true;
  15981. };
  15982. /**
  15983. * Creates a new raw 3D texture
  15984. * @param data defines the data used to create the texture
  15985. * @param width defines the width of the texture
  15986. * @param height defines the height of the texture
  15987. * @param depth defines the depth of the texture
  15988. * @param format defines the format of the texture
  15989. * @param generateMipMaps defines if the engine must generate mip levels
  15990. * @param invertY defines if data must be stored with Y axis inverted
  15991. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15992. * @param compression defines the compressed used (can be null)
  15993. * @param textureType defines the compressed used (can be null)
  15994. * @returns a new raw 3D texture (stored in an InternalTexture)
  15995. */
  15996. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  15997. if (compression === void 0) { compression = null; }
  15998. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15999. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16000. texture.baseWidth = width;
  16001. texture.baseHeight = height;
  16002. texture.baseDepth = depth;
  16003. texture.width = width;
  16004. texture.height = height;
  16005. texture.depth = depth;
  16006. texture.format = format;
  16007. texture.type = textureType;
  16008. texture.generateMipMaps = generateMipMaps;
  16009. texture.samplingMode = samplingMode;
  16010. texture.is3D = true;
  16011. if (!this._doNotHandleContextLost) {
  16012. texture._bufferView = data;
  16013. }
  16014. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16015. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16016. // Filters
  16017. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16018. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16019. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16020. if (generateMipMaps) {
  16021. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16022. }
  16023. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16024. this._internalTexturesCache.push(texture);
  16025. return texture;
  16026. };
  16027. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16028. var gl = this._gl;
  16029. if (!gl) {
  16030. return;
  16031. }
  16032. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16033. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16034. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16035. if (!noMipmap && !isCompressed) {
  16036. gl.generateMipmap(gl.TEXTURE_2D);
  16037. }
  16038. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16039. // this.resetTextureCache();
  16040. if (scene) {
  16041. scene._removePendingData(texture);
  16042. }
  16043. texture.onLoadedObservable.notifyObservers(texture);
  16044. texture.onLoadedObservable.clear();
  16045. };
  16046. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16047. var _this = this;
  16048. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16049. var maxTextureSize = this.getCaps().maxTextureSize;
  16050. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16051. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16052. var gl = this._gl;
  16053. if (!gl) {
  16054. return;
  16055. }
  16056. if (!texture._webGLTexture) {
  16057. // this.resetTextureCache();
  16058. if (scene) {
  16059. scene._removePendingData(texture);
  16060. }
  16061. return;
  16062. }
  16063. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16064. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16065. texture.baseWidth = width;
  16066. texture.baseHeight = height;
  16067. texture.width = potWidth;
  16068. texture.height = potHeight;
  16069. texture.isReady = true;
  16070. if (processFunction(potWidth, potHeight, function () {
  16071. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16072. })) {
  16073. // Returning as texture needs extra async steps
  16074. return;
  16075. }
  16076. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16077. };
  16078. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16079. // Create new RGBA data container.
  16080. var rgbaData;
  16081. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16082. rgbaData = new Float32Array(width * height * 4);
  16083. }
  16084. else {
  16085. rgbaData = new Uint32Array(width * height * 4);
  16086. }
  16087. // Convert each pixel.
  16088. for (var x = 0; x < width; x++) {
  16089. for (var y = 0; y < height; y++) {
  16090. var index = (y * width + x) * 3;
  16091. var newIndex = (y * width + x) * 4;
  16092. // Map Old Value to new value.
  16093. rgbaData[newIndex + 0] = rgbData[index + 0];
  16094. rgbaData[newIndex + 1] = rgbData[index + 1];
  16095. rgbaData[newIndex + 2] = rgbData[index + 2];
  16096. // Add fully opaque alpha channel.
  16097. rgbaData[newIndex + 3] = 1;
  16098. }
  16099. }
  16100. return rgbaData;
  16101. };
  16102. /** @hidden */
  16103. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16104. var gl = this._gl;
  16105. if (texture._framebuffer) {
  16106. gl.deleteFramebuffer(texture._framebuffer);
  16107. texture._framebuffer = null;
  16108. }
  16109. if (texture._depthStencilBuffer) {
  16110. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16111. texture._depthStencilBuffer = null;
  16112. }
  16113. if (texture._MSAAFramebuffer) {
  16114. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16115. texture._MSAAFramebuffer = null;
  16116. }
  16117. if (texture._MSAARenderBuffer) {
  16118. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16119. texture._MSAARenderBuffer = null;
  16120. }
  16121. };
  16122. /** @hidden */
  16123. Engine.prototype._releaseTexture = function (texture) {
  16124. var gl = this._gl;
  16125. this._releaseFramebufferObjects(texture);
  16126. gl.deleteTexture(texture._webGLTexture);
  16127. // Unbind channels
  16128. this.unbindAllTextures();
  16129. var index = this._internalTexturesCache.indexOf(texture);
  16130. if (index !== -1) {
  16131. this._internalTexturesCache.splice(index, 1);
  16132. }
  16133. // Integrated fixed lod samplers.
  16134. if (texture._lodTextureHigh) {
  16135. texture._lodTextureHigh.dispose();
  16136. }
  16137. if (texture._lodTextureMid) {
  16138. texture._lodTextureMid.dispose();
  16139. }
  16140. if (texture._lodTextureLow) {
  16141. texture._lodTextureLow.dispose();
  16142. }
  16143. // Set output texture of post process to null if the texture has been released/disposed
  16144. this.scenes.forEach(function (scene) {
  16145. scene.postProcesses.forEach(function (postProcess) {
  16146. if (postProcess._outputTexture == texture) {
  16147. postProcess._outputTexture = null;
  16148. }
  16149. });
  16150. scene.cameras.forEach(function (camera) {
  16151. camera._postProcesses.forEach(function (postProcess) {
  16152. if (postProcess) {
  16153. if (postProcess._outputTexture == texture) {
  16154. postProcess._outputTexture = null;
  16155. }
  16156. }
  16157. });
  16158. });
  16159. });
  16160. };
  16161. Engine.prototype.setProgram = function (program) {
  16162. if (this._currentProgram !== program) {
  16163. this._gl.useProgram(program);
  16164. this._currentProgram = program;
  16165. }
  16166. };
  16167. /**
  16168. * Binds an effect to the webGL context
  16169. * @param effect defines the effect to bind
  16170. */
  16171. Engine.prototype.bindSamplers = function (effect) {
  16172. this.setProgram(effect.getProgram());
  16173. var samplers = effect.getSamplers();
  16174. for (var index = 0; index < samplers.length; index++) {
  16175. var uniform = effect.getUniform(samplers[index]);
  16176. if (uniform) {
  16177. this._boundUniforms[index] = uniform;
  16178. }
  16179. }
  16180. this._currentEffect = null;
  16181. };
  16182. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16183. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16184. return;
  16185. }
  16186. // Remove
  16187. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16188. // Bind last to it
  16189. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16190. // Bind to dummy
  16191. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16192. };
  16193. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16194. if (!internalTexture) {
  16195. return -1;
  16196. }
  16197. internalTexture._initialSlot = channel;
  16198. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16199. if (channel !== internalTexture._designatedSlot) {
  16200. this._textureCollisions.addCount(1, false);
  16201. }
  16202. }
  16203. else {
  16204. if (channel !== internalTexture._designatedSlot) {
  16205. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16206. return internalTexture._designatedSlot;
  16207. }
  16208. else {
  16209. // No slot for this texture, let's pick a new one (if we find a free slot)
  16210. if (this._nextFreeTextureSlots.length) {
  16211. return this._nextFreeTextureSlots[0];
  16212. }
  16213. // We need to recycle the oldest bound texture, sorry.
  16214. this._textureCollisions.addCount(1, false);
  16215. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16216. }
  16217. }
  16218. }
  16219. return channel;
  16220. };
  16221. Engine.prototype._linkTrackers = function (previous, next) {
  16222. previous.next = next;
  16223. next.previous = previous;
  16224. };
  16225. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16226. var currentSlot = internalTexture._designatedSlot;
  16227. if (currentSlot === -1) {
  16228. return -1;
  16229. }
  16230. internalTexture._designatedSlot = -1;
  16231. if (this.disableTextureBindingOptimization) {
  16232. return -1;
  16233. }
  16234. // Remove from bound list
  16235. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16236. // Free the slot
  16237. this._boundTexturesCache[currentSlot] = null;
  16238. this._nextFreeTextureSlots.push(currentSlot);
  16239. return currentSlot;
  16240. };
  16241. Engine.prototype._activateCurrentTexture = function () {
  16242. if (this._currentTextureChannel !== this._activeChannel) {
  16243. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16244. this._currentTextureChannel = this._activeChannel;
  16245. }
  16246. };
  16247. /** @hidden */
  16248. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16249. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16250. if (force === void 0) { force = false; }
  16251. var wasPreviouslyBound = false;
  16252. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16253. this._activeChannel = texture._designatedSlot;
  16254. }
  16255. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16256. var isTextureForRendering = texture && texture._initialSlot > -1;
  16257. if (currentTextureBound !== texture || force) {
  16258. if (currentTextureBound) {
  16259. this._removeDesignatedSlot(currentTextureBound);
  16260. }
  16261. this._activateCurrentTexture();
  16262. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16263. this._boundTexturesCache[this._activeChannel] = texture;
  16264. if (texture) {
  16265. if (!this.disableTextureBindingOptimization) {
  16266. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16267. if (slotIndex > -1) {
  16268. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16269. }
  16270. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16271. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16272. }
  16273. texture._designatedSlot = this._activeChannel;
  16274. }
  16275. }
  16276. else if (forTextureDataUpdate) {
  16277. wasPreviouslyBound = true;
  16278. this._activateCurrentTexture();
  16279. }
  16280. if (isTextureForRendering && !forTextureDataUpdate) {
  16281. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16282. }
  16283. return wasPreviouslyBound;
  16284. };
  16285. /** @hidden */
  16286. Engine.prototype._bindTexture = function (channel, texture) {
  16287. if (channel < 0) {
  16288. return;
  16289. }
  16290. if (texture) {
  16291. channel = this._getCorrectTextureChannel(channel, texture);
  16292. }
  16293. this._activeChannel = channel;
  16294. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16295. };
  16296. /**
  16297. * Sets a texture to the webGL context from a postprocess
  16298. * @param channel defines the channel to use
  16299. * @param postProcess defines the source postprocess
  16300. */
  16301. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16302. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16303. };
  16304. /**
  16305. * Binds the output of the passed in post process to the texture channel specified
  16306. * @param channel The channel the texture should be bound to
  16307. * @param postProcess The post process which's output should be bound
  16308. */
  16309. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16310. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16311. };
  16312. /**
  16313. * Unbind all textures from the webGL context
  16314. */
  16315. Engine.prototype.unbindAllTextures = function () {
  16316. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16317. this._activeChannel = channel;
  16318. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16319. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16320. if (this.webGLVersion > 1) {
  16321. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16322. }
  16323. }
  16324. };
  16325. /**
  16326. * Sets a texture to the according uniform.
  16327. * @param channel The texture channel
  16328. * @param uniform The uniform to set
  16329. * @param texture The texture to apply
  16330. */
  16331. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16332. if (channel < 0) {
  16333. return;
  16334. }
  16335. if (uniform) {
  16336. this._boundUniforms[channel] = uniform;
  16337. }
  16338. this._setTexture(channel, texture);
  16339. };
  16340. /**
  16341. * Sets a depth stencil texture from a render target to the according uniform.
  16342. * @param channel The texture channel
  16343. * @param uniform The uniform to set
  16344. * @param texture The render target texture containing the depth stencil texture to apply
  16345. */
  16346. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16347. if (channel < 0) {
  16348. return;
  16349. }
  16350. if (uniform) {
  16351. this._boundUniforms[channel] = uniform;
  16352. }
  16353. if (!texture || !texture.depthStencilTexture) {
  16354. this._setTexture(channel, null);
  16355. }
  16356. else {
  16357. this._setTexture(channel, texture, false, true);
  16358. }
  16359. };
  16360. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16361. var uniform = this._boundUniforms[sourceSlot];
  16362. if (uniform._currentState === destination) {
  16363. return;
  16364. }
  16365. this._gl.uniform1i(uniform, destination);
  16366. uniform._currentState = destination;
  16367. };
  16368. Engine.prototype._getTextureWrapMode = function (mode) {
  16369. switch (mode) {
  16370. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16371. return this._gl.REPEAT;
  16372. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16373. return this._gl.CLAMP_TO_EDGE;
  16374. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16375. return this._gl.MIRRORED_REPEAT;
  16376. }
  16377. return this._gl.REPEAT;
  16378. };
  16379. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16380. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16381. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16382. // Not ready?
  16383. if (!texture) {
  16384. if (this._boundTexturesCache[channel] != null) {
  16385. this._activeChannel = channel;
  16386. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16387. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16388. if (this.webGLVersion > 1) {
  16389. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16390. }
  16391. }
  16392. return false;
  16393. }
  16394. // Video
  16395. if (texture.video) {
  16396. this._activeChannel = channel;
  16397. texture.update();
  16398. }
  16399. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16400. texture.delayLoad();
  16401. return false;
  16402. }
  16403. var internalTexture;
  16404. if (depthStencilTexture) {
  16405. internalTexture = texture.depthStencilTexture;
  16406. }
  16407. else if (texture.isReady()) {
  16408. internalTexture = texture.getInternalTexture();
  16409. }
  16410. else if (texture.isCube) {
  16411. internalTexture = this.emptyCubeTexture;
  16412. }
  16413. else if (texture.is3D) {
  16414. internalTexture = this.emptyTexture3D;
  16415. }
  16416. else {
  16417. internalTexture = this.emptyTexture;
  16418. }
  16419. if (!isPartOfTextureArray) {
  16420. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16421. }
  16422. var needToBind = true;
  16423. if (this._boundTexturesCache[channel] === internalTexture) {
  16424. this._moveBoundTextureOnTop(internalTexture);
  16425. if (!isPartOfTextureArray) {
  16426. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16427. }
  16428. needToBind = false;
  16429. }
  16430. this._activeChannel = channel;
  16431. if (internalTexture && internalTexture.is3D) {
  16432. if (needToBind) {
  16433. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16434. }
  16435. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16436. internalTexture._cachedWrapU = texture.wrapU;
  16437. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16438. }
  16439. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16440. internalTexture._cachedWrapV = texture.wrapV;
  16441. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16442. }
  16443. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16444. internalTexture._cachedWrapR = texture.wrapR;
  16445. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16446. }
  16447. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16448. }
  16449. else if (internalTexture && internalTexture.isCube) {
  16450. if (needToBind) {
  16451. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16452. }
  16453. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16454. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16455. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16456. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16457. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16458. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16459. }
  16460. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16461. }
  16462. else {
  16463. if (needToBind) {
  16464. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16465. }
  16466. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16467. internalTexture._cachedWrapU = texture.wrapU;
  16468. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16469. }
  16470. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16471. internalTexture._cachedWrapV = texture.wrapV;
  16472. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16473. }
  16474. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16475. }
  16476. return true;
  16477. };
  16478. /**
  16479. * Sets an array of texture to the webGL context
  16480. * @param channel defines the channel where the texture array must be set
  16481. * @param uniform defines the associated uniform location
  16482. * @param textures defines the array of textures to bind
  16483. */
  16484. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16485. if (channel < 0 || !uniform) {
  16486. return;
  16487. }
  16488. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16489. this._textureUnits = new Int32Array(textures.length);
  16490. }
  16491. for (var i = 0; i < textures.length; i++) {
  16492. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16493. }
  16494. this._gl.uniform1iv(uniform, this._textureUnits);
  16495. for (var index = 0; index < textures.length; index++) {
  16496. this._setTexture(this._textureUnits[index], textures[index], true);
  16497. }
  16498. };
  16499. /** @hidden */
  16500. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16501. var internalTexture = texture.getInternalTexture();
  16502. if (!internalTexture) {
  16503. return;
  16504. }
  16505. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16506. var value = texture.anisotropicFilteringLevel;
  16507. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16508. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16509. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16510. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16511. }
  16512. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16513. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16514. internalTexture._cachedAnisotropicFilteringLevel = value;
  16515. }
  16516. };
  16517. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16518. this._bindTextureDirectly(target, texture, true, true);
  16519. this._gl.texParameterf(target, parameter, value);
  16520. };
  16521. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16522. if (texture) {
  16523. this._bindTextureDirectly(target, texture, true, true);
  16524. }
  16525. this._gl.texParameteri(target, parameter, value);
  16526. };
  16527. /**
  16528. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16529. * @param x defines the x coordinate of the rectangle where pixels must be read
  16530. * @param y defines the y coordinate of the rectangle where pixels must be read
  16531. * @param width defines the width of the rectangle where pixels must be read
  16532. * @param height defines the height of the rectangle where pixels must be read
  16533. * @returns a Uint8Array containing RGBA colors
  16534. */
  16535. Engine.prototype.readPixels = function (x, y, width, height) {
  16536. var data = new Uint8Array(height * width * 4);
  16537. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16538. return data;
  16539. };
  16540. /**
  16541. * Add an externaly attached data from its key.
  16542. * This method call will fail and return false, if such key already exists.
  16543. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16544. * @param key the unique key that identifies the data
  16545. * @param data the data object to associate to the key for this Engine instance
  16546. * @return true if no such key were already present and the data was added successfully, false otherwise
  16547. */
  16548. Engine.prototype.addExternalData = function (key, data) {
  16549. if (!this._externalData) {
  16550. this._externalData = new BABYLON.StringDictionary();
  16551. }
  16552. return this._externalData.add(key, data);
  16553. };
  16554. /**
  16555. * Get an externaly attached data from its key
  16556. * @param key the unique key that identifies the data
  16557. * @return the associated data, if present (can be null), or undefined if not present
  16558. */
  16559. Engine.prototype.getExternalData = function (key) {
  16560. if (!this._externalData) {
  16561. this._externalData = new BABYLON.StringDictionary();
  16562. }
  16563. return this._externalData.get(key);
  16564. };
  16565. /**
  16566. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16567. * @param key the unique key that identifies the data
  16568. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16569. * @return the associated data, can be null if the factory returned null.
  16570. */
  16571. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16572. if (!this._externalData) {
  16573. this._externalData = new BABYLON.StringDictionary();
  16574. }
  16575. return this._externalData.getOrAddWithFactory(key, factory);
  16576. };
  16577. /**
  16578. * Remove an externaly attached data from the Engine instance
  16579. * @param key the unique key that identifies the data
  16580. * @return true if the data was successfully removed, false if it doesn't exist
  16581. */
  16582. Engine.prototype.removeExternalData = function (key) {
  16583. if (!this._externalData) {
  16584. this._externalData = new BABYLON.StringDictionary();
  16585. }
  16586. return this._externalData.remove(key);
  16587. };
  16588. /**
  16589. * Unbind all vertex attributes from the webGL context
  16590. */
  16591. Engine.prototype.unbindAllAttributes = function () {
  16592. if (this._mustWipeVertexAttributes) {
  16593. this._mustWipeVertexAttributes = false;
  16594. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16595. this._gl.disableVertexAttribArray(i);
  16596. this._vertexAttribArraysEnabled[i] = false;
  16597. this._currentBufferPointers[i].active = false;
  16598. }
  16599. return;
  16600. }
  16601. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16602. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16603. continue;
  16604. }
  16605. this._gl.disableVertexAttribArray(i);
  16606. this._vertexAttribArraysEnabled[i] = false;
  16607. this._currentBufferPointers[i].active = false;
  16608. }
  16609. };
  16610. /**
  16611. * 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
  16612. */
  16613. Engine.prototype.releaseEffects = function () {
  16614. for (var name in this._compiledEffects) {
  16615. this._deleteProgram(this._compiledEffects[name]._program);
  16616. }
  16617. this._compiledEffects = {};
  16618. };
  16619. /**
  16620. * Dispose and release all associated resources
  16621. */
  16622. Engine.prototype.dispose = function () {
  16623. this.hideLoadingUI();
  16624. this.stopRenderLoop();
  16625. // Release postProcesses
  16626. while (this.postProcesses.length) {
  16627. this.postProcesses[0].dispose();
  16628. }
  16629. // Empty texture
  16630. if (this._emptyTexture) {
  16631. this._releaseTexture(this._emptyTexture);
  16632. this._emptyTexture = null;
  16633. }
  16634. if (this._emptyCubeTexture) {
  16635. this._releaseTexture(this._emptyCubeTexture);
  16636. this._emptyCubeTexture = null;
  16637. }
  16638. // Rescale PP
  16639. if (this._rescalePostProcess) {
  16640. this._rescalePostProcess.dispose();
  16641. }
  16642. // Release scenes
  16643. while (this.scenes.length) {
  16644. this.scenes[0].dispose();
  16645. }
  16646. // Release audio engine
  16647. if (Engine.audioEngine) {
  16648. Engine.audioEngine.dispose();
  16649. }
  16650. // Release effects
  16651. this.releaseEffects();
  16652. // Unbind
  16653. this.unbindAllAttributes();
  16654. this._boundUniforms = [];
  16655. if (this._dummyFramebuffer) {
  16656. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16657. }
  16658. //WebVR
  16659. this.disableVR();
  16660. // Events
  16661. if (BABYLON.Tools.IsWindowObjectExist()) {
  16662. window.removeEventListener("blur", this._onBlur);
  16663. window.removeEventListener("focus", this._onFocus);
  16664. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16665. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16666. if (this._renderingCanvas) {
  16667. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16668. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16669. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16670. if (!this._doNotHandleContextLost) {
  16671. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16672. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16673. }
  16674. }
  16675. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16676. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16677. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16678. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16679. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16680. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16681. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16682. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16683. if (this._onVrDisplayConnect) {
  16684. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16685. if (this._onVrDisplayDisconnect) {
  16686. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16687. }
  16688. if (this._onVrDisplayPresentChange) {
  16689. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16690. }
  16691. this._onVrDisplayConnect = null;
  16692. this._onVrDisplayDisconnect = null;
  16693. }
  16694. }
  16695. // Remove from Instances
  16696. var index = Engine.Instances.indexOf(this);
  16697. if (index >= 0) {
  16698. Engine.Instances.splice(index, 1);
  16699. }
  16700. this._workingCanvas = null;
  16701. this._workingContext = null;
  16702. this._currentBufferPointers = [];
  16703. this._renderingCanvas = null;
  16704. this._currentProgram = null;
  16705. this._bindedRenderFunction = null;
  16706. this.onResizeObservable.clear();
  16707. this.onCanvasBlurObservable.clear();
  16708. this.onCanvasFocusObservable.clear();
  16709. this.onCanvasPointerOutObservable.clear();
  16710. this.onBeginFrameObservable.clear();
  16711. this.onEndFrameObservable.clear();
  16712. BABYLON.Effect.ResetCache();
  16713. // Abort active requests
  16714. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16715. var request = _a[_i];
  16716. request.abort();
  16717. }
  16718. };
  16719. // Loading screen
  16720. /**
  16721. * Display the loading screen
  16722. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16723. */
  16724. Engine.prototype.displayLoadingUI = function () {
  16725. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16726. return;
  16727. }
  16728. var loadingScreen = this.loadingScreen;
  16729. if (loadingScreen) {
  16730. loadingScreen.displayLoadingUI();
  16731. }
  16732. };
  16733. /**
  16734. * Hide the loading screen
  16735. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16736. */
  16737. Engine.prototype.hideLoadingUI = function () {
  16738. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16739. return;
  16740. }
  16741. var loadingScreen = this.loadingScreen;
  16742. if (loadingScreen) {
  16743. loadingScreen.hideLoadingUI();
  16744. }
  16745. };
  16746. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16747. /**
  16748. * Gets the current loading screen object
  16749. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16750. */
  16751. get: function () {
  16752. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16753. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16754. return this._loadingScreen;
  16755. },
  16756. /**
  16757. * Sets the current loading screen object
  16758. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16759. */
  16760. set: function (loadingScreen) {
  16761. this._loadingScreen = loadingScreen;
  16762. },
  16763. enumerable: true,
  16764. configurable: true
  16765. });
  16766. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16767. /**
  16768. * Sets the current loading screen text
  16769. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16770. */
  16771. set: function (text) {
  16772. this.loadingScreen.loadingUIText = text;
  16773. },
  16774. enumerable: true,
  16775. configurable: true
  16776. });
  16777. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16778. /**
  16779. * Sets the current loading screen background color
  16780. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16781. */
  16782. set: function (color) {
  16783. this.loadingScreen.loadingUIBackgroundColor = color;
  16784. },
  16785. enumerable: true,
  16786. configurable: true
  16787. });
  16788. /**
  16789. * Attach a new callback raised when context lost event is fired
  16790. * @param callback defines the callback to call
  16791. */
  16792. Engine.prototype.attachContextLostEvent = function (callback) {
  16793. if (this._renderingCanvas) {
  16794. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16795. }
  16796. };
  16797. /**
  16798. * Attach a new callback raised when context restored event is fired
  16799. * @param callback defines the callback to call
  16800. */
  16801. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16802. if (this._renderingCanvas) {
  16803. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16804. }
  16805. };
  16806. /**
  16807. * Gets the source code of the vertex shader associated with a specific webGL program
  16808. * @param program defines the program to use
  16809. * @returns a string containing the source code of the vertex shader associated with the program
  16810. */
  16811. Engine.prototype.getVertexShaderSource = function (program) {
  16812. var shaders = this._gl.getAttachedShaders(program);
  16813. if (!shaders) {
  16814. return null;
  16815. }
  16816. return this._gl.getShaderSource(shaders[0]);
  16817. };
  16818. /**
  16819. * Gets the source code of the fragment shader associated with a specific webGL program
  16820. * @param program defines the program to use
  16821. * @returns a string containing the source code of the fragment shader associated with the program
  16822. */
  16823. Engine.prototype.getFragmentShaderSource = function (program) {
  16824. var shaders = this._gl.getAttachedShaders(program);
  16825. if (!shaders) {
  16826. return null;
  16827. }
  16828. return this._gl.getShaderSource(shaders[1]);
  16829. };
  16830. /**
  16831. * Get the current error code of the webGL context
  16832. * @returns the error code
  16833. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16834. */
  16835. Engine.prototype.getError = function () {
  16836. return this._gl.getError();
  16837. };
  16838. // FPS
  16839. /**
  16840. * Gets the current framerate
  16841. * @returns a number representing the framerate
  16842. */
  16843. Engine.prototype.getFps = function () {
  16844. return this._fps;
  16845. };
  16846. /**
  16847. * Gets the time spent between current and previous frame
  16848. * @returns a number representing the delta time in ms
  16849. */
  16850. Engine.prototype.getDeltaTime = function () {
  16851. return this._deltaTime;
  16852. };
  16853. Engine.prototype._measureFps = function () {
  16854. this._performanceMonitor.sampleFrame();
  16855. this._fps = this._performanceMonitor.averageFPS;
  16856. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16857. };
  16858. /** @hidden */
  16859. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16860. if (faceIndex === void 0) { faceIndex = -1; }
  16861. if (level === void 0) { level = 0; }
  16862. var gl = this._gl;
  16863. if (!this._dummyFramebuffer) {
  16864. var dummy = gl.createFramebuffer();
  16865. if (!dummy) {
  16866. throw new Error("Unable to create dummy framebuffer");
  16867. }
  16868. this._dummyFramebuffer = dummy;
  16869. }
  16870. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16871. if (faceIndex > -1) {
  16872. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16873. }
  16874. else {
  16875. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16876. }
  16877. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16878. var buffer;
  16879. switch (readType) {
  16880. case gl.UNSIGNED_BYTE:
  16881. buffer = new Uint8Array(4 * width * height);
  16882. readType = gl.UNSIGNED_BYTE;
  16883. break;
  16884. default:
  16885. buffer = new Float32Array(4 * width * height);
  16886. readType = gl.FLOAT;
  16887. break;
  16888. }
  16889. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16890. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16891. return buffer;
  16892. };
  16893. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16894. if (this._webGLVersion > 1) {
  16895. return this._caps.colorBufferFloat;
  16896. }
  16897. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16898. };
  16899. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16900. if (this._webGLVersion > 1) {
  16901. return this._caps.colorBufferFloat;
  16902. }
  16903. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16904. };
  16905. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16906. Engine.prototype._canRenderToFramebuffer = function (type) {
  16907. var gl = this._gl;
  16908. //clear existing errors
  16909. while (gl.getError() !== gl.NO_ERROR) { }
  16910. var successful = true;
  16911. var texture = gl.createTexture();
  16912. gl.bindTexture(gl.TEXTURE_2D, texture);
  16913. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16914. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16915. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16916. var fb = gl.createFramebuffer();
  16917. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16918. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16919. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16920. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16921. successful = successful && (gl.getError() === gl.NO_ERROR);
  16922. //try render by clearing frame buffer's color buffer
  16923. if (successful) {
  16924. gl.clear(gl.COLOR_BUFFER_BIT);
  16925. successful = successful && (gl.getError() === gl.NO_ERROR);
  16926. }
  16927. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16928. if (successful) {
  16929. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16930. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16931. var readFormat = gl.RGBA;
  16932. var readType = gl.UNSIGNED_BYTE;
  16933. var buffer = new Uint8Array(4);
  16934. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16935. successful = successful && (gl.getError() === gl.NO_ERROR);
  16936. }
  16937. //clean up
  16938. gl.deleteTexture(texture);
  16939. gl.deleteFramebuffer(fb);
  16940. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16941. //clear accumulated errors
  16942. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16943. return successful;
  16944. };
  16945. /** @hidden */
  16946. Engine.prototype._getWebGLTextureType = function (type) {
  16947. if (this._webGLVersion === 1) {
  16948. switch (type) {
  16949. case Engine.TEXTURETYPE_FLOAT:
  16950. return this._gl.FLOAT;
  16951. case Engine.TEXTURETYPE_HALF_FLOAT:
  16952. return this._gl.HALF_FLOAT_OES;
  16953. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  16954. return this._gl.UNSIGNED_BYTE;
  16955. }
  16956. return this._gl.UNSIGNED_BYTE;
  16957. }
  16958. switch (type) {
  16959. case Engine.TEXTURETYPE_BYTE:
  16960. return this._gl.BYTE;
  16961. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  16962. return this._gl.UNSIGNED_BYTE;
  16963. case Engine.TEXTURETYPE_SHORT:
  16964. return this._gl.SHORT;
  16965. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  16966. return this._gl.UNSIGNED_SHORT;
  16967. case Engine.TEXTURETYPE_INT:
  16968. return this._gl.INT;
  16969. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  16970. return this._gl.UNSIGNED_INT;
  16971. case Engine.TEXTURETYPE_FLOAT:
  16972. return this._gl.FLOAT;
  16973. case Engine.TEXTURETYPE_HALF_FLOAT:
  16974. return this._gl.HALF_FLOAT;
  16975. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  16976. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  16977. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  16978. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  16979. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  16980. return this._gl.UNSIGNED_SHORT_5_6_5;
  16981. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  16982. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  16983. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  16984. return this._gl.UNSIGNED_INT_24_8;
  16985. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  16986. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  16987. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  16988. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  16989. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  16990. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  16991. }
  16992. return this._gl.UNSIGNED_BYTE;
  16993. };
  16994. ;
  16995. Engine.prototype._getInternalFormat = function (format) {
  16996. var internalFormat = this._gl.RGBA;
  16997. switch (format) {
  16998. case Engine.TEXTUREFORMAT_ALPHA:
  16999. internalFormat = this._gl.ALPHA;
  17000. break;
  17001. case Engine.TEXTUREFORMAT_LUMINANCE:
  17002. internalFormat = this._gl.LUMINANCE;
  17003. break;
  17004. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17005. internalFormat = this._gl.LUMINANCE_ALPHA;
  17006. break;
  17007. case Engine.TEXTUREFORMAT_RED:
  17008. internalFormat = this._gl.RED;
  17009. break;
  17010. case Engine.TEXTUREFORMAT_RG:
  17011. internalFormat = this._gl.RG;
  17012. break;
  17013. case Engine.TEXTUREFORMAT_RGB:
  17014. internalFormat = this._gl.RGB;
  17015. break;
  17016. case Engine.TEXTUREFORMAT_RGBA:
  17017. internalFormat = this._gl.RGBA;
  17018. break;
  17019. }
  17020. if (this._webGLVersion > 1) {
  17021. switch (format) {
  17022. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17023. internalFormat = this._gl.RED_INTEGER;
  17024. break;
  17025. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17026. internalFormat = this._gl.RG_INTEGER;
  17027. break;
  17028. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17029. internalFormat = this._gl.RGB_INTEGER;
  17030. break;
  17031. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17032. internalFormat = this._gl.RGBA_INTEGER;
  17033. break;
  17034. }
  17035. }
  17036. return internalFormat;
  17037. };
  17038. /** @hidden */
  17039. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17040. if (this._webGLVersion === 1) {
  17041. if (format !== undefined) {
  17042. switch (format) {
  17043. case Engine.TEXTUREFORMAT_ALPHA:
  17044. return this._gl.ALPHA;
  17045. case Engine.TEXTUREFORMAT_LUMINANCE:
  17046. return this._gl.LUMINANCE;
  17047. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17048. return this._gl.LUMINANCE_ALPHA;
  17049. }
  17050. }
  17051. return this._gl.RGBA;
  17052. }
  17053. switch (type) {
  17054. case Engine.TEXTURETYPE_BYTE:
  17055. switch (format) {
  17056. case Engine.TEXTUREFORMAT_RED:
  17057. return this._gl.R8_SNORM;
  17058. case Engine.TEXTUREFORMAT_RG:
  17059. return this._gl.RG8_SNORM;
  17060. case Engine.TEXTUREFORMAT_RGB:
  17061. return this._gl.RGB8_SNORM;
  17062. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17063. return this._gl.R8I;
  17064. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17065. return this._gl.RG8I;
  17066. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17067. return this._gl.RGB8I;
  17068. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17069. return this._gl.RGBA8I;
  17070. default:
  17071. return this._gl.RGBA8_SNORM;
  17072. }
  17073. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17074. switch (format) {
  17075. case Engine.TEXTUREFORMAT_RED:
  17076. return this._gl.R8;
  17077. case Engine.TEXTUREFORMAT_RG:
  17078. return this._gl.RG8;
  17079. case Engine.TEXTUREFORMAT_RGB:
  17080. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17081. case Engine.TEXTUREFORMAT_RGBA:
  17082. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17083. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17084. return this._gl.R8UI;
  17085. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17086. return this._gl.RG8UI;
  17087. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17088. return this._gl.RGB8UI;
  17089. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17090. return this._gl.RGBA8UI;
  17091. default:
  17092. return this._gl.RGBA8;
  17093. }
  17094. case Engine.TEXTURETYPE_SHORT:
  17095. switch (format) {
  17096. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17097. return this._gl.R16I;
  17098. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17099. return this._gl.RG16I;
  17100. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17101. return this._gl.RGB16I;
  17102. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17103. return this._gl.RGBA16I;
  17104. default:
  17105. return this._gl.RGBA16I;
  17106. }
  17107. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17108. switch (format) {
  17109. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17110. return this._gl.R16UI;
  17111. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17112. return this._gl.RG16UI;
  17113. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17114. return this._gl.RGB16UI;
  17115. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17116. return this._gl.RGBA16UI;
  17117. default:
  17118. return this._gl.RGBA16UI;
  17119. }
  17120. case Engine.TEXTURETYPE_INT:
  17121. switch (format) {
  17122. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17123. return this._gl.R32I;
  17124. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17125. return this._gl.RG32I;
  17126. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17127. return this._gl.RGB32I;
  17128. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17129. return this._gl.RGBA32I;
  17130. default:
  17131. return this._gl.RGBA32I;
  17132. }
  17133. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17134. switch (format) {
  17135. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17136. return this._gl.R32UI;
  17137. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17138. return this._gl.RG32UI;
  17139. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17140. return this._gl.RGB32UI;
  17141. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17142. return this._gl.RGBA32UI;
  17143. default:
  17144. return this._gl.RGBA32UI;
  17145. }
  17146. case Engine.TEXTURETYPE_FLOAT:
  17147. switch (format) {
  17148. case Engine.TEXTUREFORMAT_RED:
  17149. return this._gl.R32F; // By default. Other possibility is R16F.
  17150. case Engine.TEXTUREFORMAT_RG:
  17151. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17152. case Engine.TEXTUREFORMAT_RGB:
  17153. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17154. case Engine.TEXTUREFORMAT_RGBA:
  17155. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17156. default:
  17157. return this._gl.RGBA32F;
  17158. }
  17159. case Engine.TEXTURETYPE_HALF_FLOAT:
  17160. switch (format) {
  17161. case Engine.TEXTUREFORMAT_RED:
  17162. return this._gl.R16F;
  17163. case Engine.TEXTUREFORMAT_RG:
  17164. return this._gl.RG16F;
  17165. case Engine.TEXTUREFORMAT_RGB:
  17166. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17167. case Engine.TEXTUREFORMAT_RGBA:
  17168. return this._gl.RGBA16F;
  17169. default:
  17170. return this._gl.RGBA16F;
  17171. }
  17172. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17173. return this._gl.RGB565;
  17174. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17175. return this._gl.R11F_G11F_B10F;
  17176. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17177. return this._gl.RGB9_E5;
  17178. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17179. return this._gl.RGBA4;
  17180. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17181. return this._gl.RGB5_A1;
  17182. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17183. switch (format) {
  17184. case Engine.TEXTUREFORMAT_RGBA:
  17185. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17186. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17187. return this._gl.RGB10_A2UI;
  17188. default:
  17189. return this._gl.RGB10_A2;
  17190. }
  17191. }
  17192. return this._gl.RGBA8;
  17193. };
  17194. ;
  17195. /** @hidden */
  17196. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17197. if (type === Engine.TEXTURETYPE_FLOAT) {
  17198. return this._gl.RGBA32F;
  17199. }
  17200. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17201. return this._gl.RGBA16F;
  17202. }
  17203. return this._gl.RGBA8;
  17204. };
  17205. ;
  17206. /** @hidden */
  17207. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17208. var _this = this;
  17209. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17210. this._activeRequests.push(request);
  17211. request.onCompleteObservable.add(function (request) {
  17212. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17213. });
  17214. return request;
  17215. };
  17216. /** @hidden */
  17217. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17218. var _this = this;
  17219. return new Promise(function (resolve, reject) {
  17220. _this._loadFile(url, function (data) {
  17221. resolve(data);
  17222. }, undefined, database, useArrayBuffer, function (request, exception) {
  17223. reject(exception);
  17224. });
  17225. });
  17226. };
  17227. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17228. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17229. var onload = function (data) {
  17230. loadedFiles[index] = data;
  17231. loadedFiles._internalCount++;
  17232. if (loadedFiles._internalCount === 6) {
  17233. onfinish(loadedFiles);
  17234. }
  17235. };
  17236. var onerror = function (request, exception) {
  17237. if (onErrorCallBack && request) {
  17238. onErrorCallBack(request.status + " " + request.statusText, exception);
  17239. }
  17240. };
  17241. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17242. };
  17243. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17244. if (onError === void 0) { onError = null; }
  17245. var loadedFiles = [];
  17246. loadedFiles._internalCount = 0;
  17247. for (var index = 0; index < 6; index++) {
  17248. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17249. }
  17250. };
  17251. // Statics
  17252. /**
  17253. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17254. * @returns true if the engine can be created
  17255. * @ignorenaming
  17256. */
  17257. Engine.isSupported = function () {
  17258. try {
  17259. var tempcanvas = document.createElement("canvas");
  17260. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17261. return gl != null && !!window.WebGLRenderingContext;
  17262. }
  17263. catch (e) {
  17264. return false;
  17265. }
  17266. };
  17267. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17268. Engine.ExceptionList = [
  17269. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17270. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17271. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17272. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17273. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17274. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17275. ];
  17276. /** Gets the list of created engines */
  17277. Engine.Instances = new Array();
  17278. /**
  17279. * Hidden
  17280. */
  17281. Engine._TextureLoaders = [];
  17282. // Const statics
  17283. /** Defines that alpha blending is disabled */
  17284. Engine.ALPHA_DISABLE = 0;
  17285. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17286. Engine.ALPHA_ADD = 1;
  17287. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17288. Engine.ALPHA_COMBINE = 2;
  17289. /** Defines that alpha blending to DEST - SRC * DEST */
  17290. Engine.ALPHA_SUBTRACT = 3;
  17291. /** Defines that alpha blending to SRC * DEST */
  17292. Engine.ALPHA_MULTIPLY = 4;
  17293. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17294. Engine.ALPHA_MAXIMIZED = 5;
  17295. /** Defines that alpha blending to SRC + DEST */
  17296. Engine.ALPHA_ONEONE = 6;
  17297. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17298. Engine.ALPHA_PREMULTIPLIED = 7;
  17299. /**
  17300. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17301. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17302. */
  17303. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17304. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17305. Engine.ALPHA_INTERPOLATE = 9;
  17306. /**
  17307. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17308. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17309. */
  17310. Engine.ALPHA_SCREENMODE = 10;
  17311. /** Defines that the ressource is not delayed*/
  17312. Engine.DELAYLOADSTATE_NONE = 0;
  17313. /** Defines that the ressource was successfully delay loaded */
  17314. Engine.DELAYLOADSTATE_LOADED = 1;
  17315. /** Defines that the ressource is currently delay loading */
  17316. Engine.DELAYLOADSTATE_LOADING = 2;
  17317. /** Defines that the ressource is delayed and has not started loading */
  17318. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17319. // Depht or Stencil test Constants.
  17320. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17321. Engine.NEVER = 0x0200;
  17322. /** 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 */
  17323. Engine.ALWAYS = 0x0207;
  17324. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17325. Engine.LESS = 0x0201;
  17326. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17327. Engine.EQUAL = 0x0202;
  17328. /** 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 */
  17329. Engine.LEQUAL = 0x0203;
  17330. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17331. Engine.GREATER = 0x0204;
  17332. /** 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 */
  17333. Engine.GEQUAL = 0x0206;
  17334. /** 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 */
  17335. Engine.NOTEQUAL = 0x0205;
  17336. // Stencil Actions Constants.
  17337. /** Passed to stencilOperation to specify that stencil value must be kept */
  17338. Engine.KEEP = 0x1E00;
  17339. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17340. Engine.REPLACE = 0x1E01;
  17341. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17342. Engine.INCR = 0x1E02;
  17343. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17344. Engine.DECR = 0x1E03;
  17345. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17346. Engine.INVERT = 0x150A;
  17347. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17348. Engine.INCR_WRAP = 0x8507;
  17349. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17350. Engine.DECR_WRAP = 0x8508;
  17351. /** Texture is not repeating outside of 0..1 UVs */
  17352. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17353. /** Texture is repeating outside of 0..1 UVs */
  17354. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17355. /** Texture is repeating and mirrored */
  17356. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17357. /** ALPHA */
  17358. Engine.TEXTUREFORMAT_ALPHA = 0;
  17359. /** LUMINANCE */
  17360. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17361. /** LUMINANCE_ALPHA */
  17362. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17363. /** RGB */
  17364. Engine.TEXTUREFORMAT_RGB = 4;
  17365. /** RGBA */
  17366. Engine.TEXTUREFORMAT_RGBA = 5;
  17367. /** RED */
  17368. Engine.TEXTUREFORMAT_RED = 6;
  17369. /** RED (2nd reference) */
  17370. Engine.TEXTUREFORMAT_R = 6;
  17371. /** RG */
  17372. Engine.TEXTUREFORMAT_RG = 7;
  17373. /** RED_INTEGER */
  17374. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17375. /** RED_INTEGER (2nd reference) */
  17376. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17377. /** RG_INTEGER */
  17378. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17379. /** RGB_INTEGER */
  17380. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17381. /** RGBA_INTEGER */
  17382. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17383. /** UNSIGNED_BYTE */
  17384. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17385. /** UNSIGNED_BYTE (2nd reference) */
  17386. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17387. /** FLOAT */
  17388. Engine.TEXTURETYPE_FLOAT = 1;
  17389. /** HALF_FLOAT */
  17390. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17391. /** BYTE */
  17392. Engine.TEXTURETYPE_BYTE = 3;
  17393. /** SHORT */
  17394. Engine.TEXTURETYPE_SHORT = 4;
  17395. /** UNSIGNED_SHORT */
  17396. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17397. /** INT */
  17398. Engine.TEXTURETYPE_INT = 6;
  17399. /** UNSIGNED_INT */
  17400. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17401. /** UNSIGNED_SHORT_4_4_4_4 */
  17402. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17403. /** UNSIGNED_SHORT_5_5_5_1 */
  17404. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17405. /** UNSIGNED_SHORT_5_6_5 */
  17406. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17407. /** UNSIGNED_INT_2_10_10_10_REV */
  17408. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17409. /** UNSIGNED_INT_24_8 */
  17410. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17411. /** UNSIGNED_INT_10F_11F_11F_REV */
  17412. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17413. /** UNSIGNED_INT_5_9_9_9_REV */
  17414. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17415. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17416. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17417. /** nearest is mag = nearest and min = nearest and mip = linear */
  17418. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17419. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17420. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17421. /** Trilinear is mag = linear and min = linear and mip = linear */
  17422. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17423. /** nearest is mag = nearest and min = nearest and mip = linear */
  17424. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17425. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17426. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17427. /** Trilinear is mag = linear and min = linear and mip = linear */
  17428. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17429. /** mag = nearest and min = nearest and mip = nearest */
  17430. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17431. /** mag = nearest and min = linear and mip = nearest */
  17432. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17433. /** mag = nearest and min = linear and mip = linear */
  17434. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17435. /** mag = nearest and min = linear and mip = none */
  17436. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17437. /** mag = nearest and min = nearest and mip = none */
  17438. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17439. /** mag = linear and min = nearest and mip = nearest */
  17440. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17441. /** mag = linear and min = nearest and mip = linear */
  17442. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17443. /** mag = linear and min = linear and mip = none */
  17444. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17445. /** mag = linear and min = nearest and mip = none */
  17446. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17447. /** Explicit coordinates mode */
  17448. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17449. /** Spherical coordinates mode */
  17450. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17451. /** Planar coordinates mode */
  17452. Engine.TEXTURE_PLANAR_MODE = 2;
  17453. /** Cubic coordinates mode */
  17454. Engine.TEXTURE_CUBIC_MODE = 3;
  17455. /** Projection coordinates mode */
  17456. Engine.TEXTURE_PROJECTION_MODE = 4;
  17457. /** Skybox coordinates mode */
  17458. Engine.TEXTURE_SKYBOX_MODE = 5;
  17459. /** Inverse Cubic coordinates mode */
  17460. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17461. /** Equirectangular coordinates mode */
  17462. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17463. /** Equirectangular Fixed coordinates mode */
  17464. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17465. /** Equirectangular Fixed Mirrored coordinates mode */
  17466. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17467. // Texture rescaling mode
  17468. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17469. Engine.SCALEMODE_FLOOR = 1;
  17470. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17471. Engine.SCALEMODE_NEAREST = 2;
  17472. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17473. Engine.SCALEMODE_CEILING = 3;
  17474. // Updatable statics so stick with vars here
  17475. /**
  17476. * Gets or sets the epsilon value used by collision engine
  17477. */
  17478. Engine.CollisionsEpsilon = 0.001;
  17479. /**
  17480. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17481. */
  17482. Engine.CodeRepository = "src/";
  17483. /**
  17484. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17485. */
  17486. Engine.ShadersRepository = "src/Shaders/";
  17487. return Engine;
  17488. }());
  17489. BABYLON.Engine = Engine;
  17490. })(BABYLON || (BABYLON = {}));
  17491. //# sourceMappingURL=babylon.engine.js.map
  17492. var BABYLON;
  17493. (function (BABYLON) {
  17494. /**
  17495. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17496. */
  17497. var Node = /** @class */ (function () {
  17498. /**
  17499. * Creates a new Node
  17500. * @param {string} name - the name and id to be given to this node
  17501. * @param {BABYLON.Scene} the scene this node will be added to
  17502. */
  17503. function Node(name, scene) {
  17504. if (scene === void 0) { scene = null; }
  17505. /**
  17506. * Gets or sets a string used to store user defined state for the node
  17507. */
  17508. this.state = "";
  17509. /**
  17510. * Gets or sets an object used to store user defined information for the node
  17511. */
  17512. this.metadata = null;
  17513. /**
  17514. * Gets or sets a boolean used to define if the node must be serialized
  17515. */
  17516. this.doNotSerialize = false;
  17517. /** @hidden */
  17518. this._isDisposed = false;
  17519. /**
  17520. * Gets a list of Animations associated with the node
  17521. */
  17522. this.animations = new Array();
  17523. this._ranges = {};
  17524. this._isEnabled = true;
  17525. this._isReady = true;
  17526. /** @hidden */
  17527. this._currentRenderId = -1;
  17528. this._parentRenderId = -1;
  17529. this._childRenderId = -1;
  17530. this._animationPropertiesOverride = null;
  17531. /**
  17532. * An event triggered when the mesh is disposed
  17533. */
  17534. this.onDisposeObservable = new BABYLON.Observable();
  17535. // Behaviors
  17536. this._behaviors = new Array();
  17537. this.name = name;
  17538. this.id = name;
  17539. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17540. this.uniqueId = this._scene.getUniqueId();
  17541. this._initCache();
  17542. }
  17543. /**
  17544. * Add a new node constructor
  17545. * @param type defines the type name of the node to construct
  17546. * @param constructorFunc defines the constructor function
  17547. */
  17548. Node.AddNodeConstructor = function (type, constructorFunc) {
  17549. this._NodeConstructors[type] = constructorFunc;
  17550. };
  17551. /**
  17552. * Returns a node constructor based on type name
  17553. * @param type defines the type name
  17554. * @param name defines the new node name
  17555. * @param scene defines the hosting scene
  17556. * @param options defines optional options to transmit to constructors
  17557. * @returns the new constructor or null
  17558. */
  17559. Node.Construct = function (type, name, scene, options) {
  17560. var constructorFunc = this._NodeConstructors[type];
  17561. if (!constructorFunc) {
  17562. return null;
  17563. }
  17564. return constructorFunc(name, scene, options);
  17565. };
  17566. /**
  17567. * Gets a boolean indicating if the node has been disposed
  17568. * @returns true if the node was disposed
  17569. */
  17570. Node.prototype.isDisposed = function () {
  17571. return this._isDisposed;
  17572. };
  17573. Object.defineProperty(Node.prototype, "parent", {
  17574. get: function () {
  17575. return this._parentNode;
  17576. },
  17577. /**
  17578. * Gets or sets the parent of the node
  17579. */
  17580. set: function (parent) {
  17581. if (this._parentNode === parent) {
  17582. return;
  17583. }
  17584. // Remove self from list of children of parent
  17585. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17586. var index = this._parentNode._children.indexOf(this);
  17587. if (index !== -1) {
  17588. this._parentNode._children.splice(index, 1);
  17589. }
  17590. }
  17591. // Store new parent
  17592. this._parentNode = parent;
  17593. // Add as child to new parent
  17594. if (this._parentNode) {
  17595. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17596. this._parentNode._children = new Array();
  17597. }
  17598. this._parentNode._children.push(this);
  17599. }
  17600. },
  17601. enumerable: true,
  17602. configurable: true
  17603. });
  17604. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17605. /**
  17606. * Gets or sets the animation properties override
  17607. */
  17608. get: function () {
  17609. if (!this._animationPropertiesOverride) {
  17610. return this._scene.animationPropertiesOverride;
  17611. }
  17612. return this._animationPropertiesOverride;
  17613. },
  17614. set: function (value) {
  17615. this._animationPropertiesOverride = value;
  17616. },
  17617. enumerable: true,
  17618. configurable: true
  17619. });
  17620. /**
  17621. * Gets a string idenfifying the name of the class
  17622. * @returns "Node" string
  17623. */
  17624. Node.prototype.getClassName = function () {
  17625. return "Node";
  17626. };
  17627. Object.defineProperty(Node.prototype, "onDispose", {
  17628. /**
  17629. * Sets a callback that will be raised when the node will be disposed
  17630. */
  17631. set: function (callback) {
  17632. if (this._onDisposeObserver) {
  17633. this.onDisposeObservable.remove(this._onDisposeObserver);
  17634. }
  17635. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17636. },
  17637. enumerable: true,
  17638. configurable: true
  17639. });
  17640. /**
  17641. * Gets the scene of the node
  17642. * @returns a {BABYLON.Scene}
  17643. */
  17644. Node.prototype.getScene = function () {
  17645. return this._scene;
  17646. };
  17647. /**
  17648. * Gets the engine of the node
  17649. * @returns a {BABYLON.Engine}
  17650. */
  17651. Node.prototype.getEngine = function () {
  17652. return this._scene.getEngine();
  17653. };
  17654. /**
  17655. * Attach a behavior to the node
  17656. * @see http://doc.babylonjs.com/features/behaviour
  17657. * @param behavior defines the behavior to attach
  17658. * @returns the current Node
  17659. */
  17660. Node.prototype.addBehavior = function (behavior) {
  17661. var _this = this;
  17662. var index = this._behaviors.indexOf(behavior);
  17663. if (index !== -1) {
  17664. return this;
  17665. }
  17666. behavior.init();
  17667. if (this._scene.isLoading) {
  17668. // We defer the attach when the scene will be loaded
  17669. this._scene.onDataLoadedObservable.addOnce(function () {
  17670. behavior.attach(_this);
  17671. });
  17672. }
  17673. else {
  17674. behavior.attach(this);
  17675. }
  17676. this._behaviors.push(behavior);
  17677. return this;
  17678. };
  17679. /**
  17680. * Remove an attached behavior
  17681. * @see http://doc.babylonjs.com/features/behaviour
  17682. * @param behavior defines the behavior to attach
  17683. * @returns the current Node
  17684. */
  17685. Node.prototype.removeBehavior = function (behavior) {
  17686. var index = this._behaviors.indexOf(behavior);
  17687. if (index === -1) {
  17688. return this;
  17689. }
  17690. this._behaviors[index].detach();
  17691. this._behaviors.splice(index, 1);
  17692. return this;
  17693. };
  17694. Object.defineProperty(Node.prototype, "behaviors", {
  17695. /**
  17696. * Gets the list of attached behaviors
  17697. * @see http://doc.babylonjs.com/features/behaviour
  17698. */
  17699. get: function () {
  17700. return this._behaviors;
  17701. },
  17702. enumerable: true,
  17703. configurable: true
  17704. });
  17705. /**
  17706. * Gets an attached behavior by name
  17707. * @param name defines the name of the behavior to look for
  17708. * @see http://doc.babylonjs.com/features/behaviour
  17709. * @returns null if behavior was not found else the requested behavior
  17710. */
  17711. Node.prototype.getBehaviorByName = function (name) {
  17712. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17713. var behavior = _a[_i];
  17714. if (behavior.name === name) {
  17715. return behavior;
  17716. }
  17717. }
  17718. return null;
  17719. };
  17720. /**
  17721. * Returns the world matrix of the node
  17722. * @returns a matrix containing the node's world matrix
  17723. */
  17724. Node.prototype.getWorldMatrix = function () {
  17725. return BABYLON.Matrix.Identity();
  17726. };
  17727. /** @hidden */
  17728. Node.prototype._getWorldMatrixDeterminant = function () {
  17729. return 1;
  17730. };
  17731. // override it in derived class if you add new variables to the cache
  17732. // and call the parent class method
  17733. /** @hidden */
  17734. Node.prototype._initCache = function () {
  17735. this._cache = {};
  17736. this._cache.parent = undefined;
  17737. };
  17738. /** @hidden */
  17739. Node.prototype.updateCache = function (force) {
  17740. if (!force && this.isSynchronized())
  17741. return;
  17742. this._cache.parent = this.parent;
  17743. this._updateCache();
  17744. };
  17745. // override it in derived class if you add new variables to the cache
  17746. // and call the parent class method if !ignoreParentClass
  17747. /** @hidden */
  17748. Node.prototype._updateCache = function (ignoreParentClass) {
  17749. };
  17750. // override it in derived class if you add new variables to the cache
  17751. /** @hidden */
  17752. Node.prototype._isSynchronized = function () {
  17753. return true;
  17754. };
  17755. /** @hidden */
  17756. Node.prototype._markSyncedWithParent = function () {
  17757. if (this.parent) {
  17758. this._parentRenderId = this.parent._childRenderId;
  17759. }
  17760. };
  17761. /** @hidden */
  17762. Node.prototype.isSynchronizedWithParent = function () {
  17763. if (!this.parent) {
  17764. return true;
  17765. }
  17766. if (this._parentRenderId !== this.parent._childRenderId) {
  17767. return false;
  17768. }
  17769. return this.parent.isSynchronized();
  17770. };
  17771. /** @hidden */
  17772. Node.prototype.isSynchronized = function (updateCache) {
  17773. var check = this.hasNewParent();
  17774. check = check || !this.isSynchronizedWithParent();
  17775. check = check || !this._isSynchronized();
  17776. if (updateCache)
  17777. this.updateCache(true);
  17778. return !check;
  17779. };
  17780. /** @hidden */
  17781. Node.prototype.hasNewParent = function (update) {
  17782. if (this._cache.parent === this.parent)
  17783. return false;
  17784. if (update)
  17785. this._cache.parent = this.parent;
  17786. return true;
  17787. };
  17788. /**
  17789. * Is this node ready to be used/rendered
  17790. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17791. * @return true if the node is ready
  17792. */
  17793. Node.prototype.isReady = function (completeCheck) {
  17794. if (completeCheck === void 0) { completeCheck = false; }
  17795. return this._isReady;
  17796. };
  17797. /**
  17798. * Is this node enabled?
  17799. * 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
  17800. * @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
  17801. * @return whether this node (and its parent) is enabled
  17802. */
  17803. Node.prototype.isEnabled = function (checkAncestors) {
  17804. if (checkAncestors === void 0) { checkAncestors = true; }
  17805. if (checkAncestors === false) {
  17806. return this._isEnabled;
  17807. }
  17808. if (this._isEnabled === false) {
  17809. return false;
  17810. }
  17811. if (this.parent !== undefined && this.parent !== null) {
  17812. return this.parent.isEnabled(checkAncestors);
  17813. }
  17814. return true;
  17815. };
  17816. /**
  17817. * Set the enabled state of this node
  17818. * @param value defines the new enabled state
  17819. */
  17820. Node.prototype.setEnabled = function (value) {
  17821. this._isEnabled = value;
  17822. };
  17823. /**
  17824. * Is this node a descendant of the given node?
  17825. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17826. * @param ancestor defines the parent node to inspect
  17827. * @returns a boolean indicating if this node is a descendant of the given node
  17828. */
  17829. Node.prototype.isDescendantOf = function (ancestor) {
  17830. if (this.parent) {
  17831. if (this.parent === ancestor) {
  17832. return true;
  17833. }
  17834. return this.parent.isDescendantOf(ancestor);
  17835. }
  17836. return false;
  17837. };
  17838. /** @hidden */
  17839. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17840. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17841. if (!this._children) {
  17842. return;
  17843. }
  17844. for (var index = 0; index < this._children.length; index++) {
  17845. var item = this._children[index];
  17846. if (!predicate || predicate(item)) {
  17847. results.push(item);
  17848. }
  17849. if (!directDescendantsOnly) {
  17850. item._getDescendants(results, false, predicate);
  17851. }
  17852. }
  17853. };
  17854. /**
  17855. * Will return all nodes that have this node as ascendant
  17856. * @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
  17857. * @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
  17858. * @return all children nodes of all types
  17859. */
  17860. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17861. var results = new Array();
  17862. this._getDescendants(results, directDescendantsOnly, predicate);
  17863. return results;
  17864. };
  17865. /**
  17866. * Get all child-meshes of this node
  17867. * @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
  17868. * @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
  17869. * @returns an array of {BABYLON.AbstractMesh}
  17870. */
  17871. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17872. var results = [];
  17873. this._getDescendants(results, directDescendantsOnly, function (node) {
  17874. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17875. });
  17876. return results;
  17877. };
  17878. /**
  17879. * Get all child-transformNodes of this node
  17880. * @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
  17881. * @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
  17882. * @returns an array of {BABYLON.TransformNode}
  17883. */
  17884. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17885. var results = [];
  17886. this._getDescendants(results, directDescendantsOnly, function (node) {
  17887. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17888. });
  17889. return results;
  17890. };
  17891. /**
  17892. * Get all direct children of this node
  17893. * @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
  17894. * @returns an array of {BABYLON.Node}
  17895. */
  17896. Node.prototype.getChildren = function (predicate) {
  17897. return this.getDescendants(true, predicate);
  17898. };
  17899. /** @hidden */
  17900. Node.prototype._setReady = function (state) {
  17901. if (state === this._isReady) {
  17902. return;
  17903. }
  17904. if (!state) {
  17905. this._isReady = false;
  17906. return;
  17907. }
  17908. if (this.onReady) {
  17909. this.onReady(this);
  17910. }
  17911. this._isReady = true;
  17912. };
  17913. /**
  17914. * Get an animation by name
  17915. * @param name defines the name of the animation to look for
  17916. * @returns null if not found else the requested animation
  17917. */
  17918. Node.prototype.getAnimationByName = function (name) {
  17919. for (var i = 0; i < this.animations.length; i++) {
  17920. var animation = this.animations[i];
  17921. if (animation.name === name) {
  17922. return animation;
  17923. }
  17924. }
  17925. return null;
  17926. };
  17927. /**
  17928. * Creates an animation range for this node
  17929. * @param name defines the name of the range
  17930. * @param from defines the starting key
  17931. * @param to defines the end key
  17932. */
  17933. Node.prototype.createAnimationRange = function (name, from, to) {
  17934. // check name not already in use
  17935. if (!this._ranges[name]) {
  17936. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17937. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17938. if (this.animations[i]) {
  17939. this.animations[i].createRange(name, from, to);
  17940. }
  17941. }
  17942. }
  17943. };
  17944. /**
  17945. * Delete a specific animation range
  17946. * @param name defines the name of the range to delete
  17947. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17948. */
  17949. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17950. if (deleteFrames === void 0) { deleteFrames = true; }
  17951. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17952. if (this.animations[i]) {
  17953. this.animations[i].deleteRange(name, deleteFrames);
  17954. }
  17955. }
  17956. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17957. };
  17958. /**
  17959. * Get an animation range by name
  17960. * @param name defines the name of the animation range to look for
  17961. * @returns null if not found else the requested animation range
  17962. */
  17963. Node.prototype.getAnimationRange = function (name) {
  17964. return this._ranges[name];
  17965. };
  17966. /**
  17967. * Will start the animation sequence
  17968. * @param name defines the range frames for animation sequence
  17969. * @param loop defines if the animation should loop (false by default)
  17970. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17971. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17972. * @returns the object created for this animation. If range does not exist, it will return null
  17973. */
  17974. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17975. var range = this.getAnimationRange(name);
  17976. if (!range) {
  17977. return null;
  17978. }
  17979. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17980. };
  17981. /**
  17982. * Serialize animation ranges into a JSON compatible object
  17983. * @returns serialization object
  17984. */
  17985. Node.prototype.serializeAnimationRanges = function () {
  17986. var serializationRanges = [];
  17987. for (var name in this._ranges) {
  17988. var localRange = this._ranges[name];
  17989. if (!localRange) {
  17990. continue;
  17991. }
  17992. var range = {};
  17993. range.name = name;
  17994. range.from = localRange.from;
  17995. range.to = localRange.to;
  17996. serializationRanges.push(range);
  17997. }
  17998. return serializationRanges;
  17999. };
  18000. /**
  18001. * Computes the world matrix of the node
  18002. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18003. * @returns the world matrix
  18004. */
  18005. Node.prototype.computeWorldMatrix = function (force) {
  18006. return BABYLON.Matrix.Identity();
  18007. };
  18008. /**
  18009. * Releases resources associated with this node.
  18010. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18011. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18012. */
  18013. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18014. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18015. if (!doNotRecurse) {
  18016. var nodes = this.getDescendants(true);
  18017. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18018. var node = nodes_1[_i];
  18019. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18020. }
  18021. }
  18022. else {
  18023. var transformNodes = this.getChildTransformNodes(true);
  18024. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18025. var transformNode = transformNodes_1[_a];
  18026. transformNode.parent = null;
  18027. transformNode.computeWorldMatrix(true);
  18028. }
  18029. }
  18030. this.parent = null;
  18031. // Callback
  18032. this.onDisposeObservable.notifyObservers(this);
  18033. this.onDisposeObservable.clear();
  18034. // Behaviors
  18035. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18036. var behavior = _c[_b];
  18037. behavior.detach();
  18038. }
  18039. this._behaviors = [];
  18040. this._isDisposed = true;
  18041. };
  18042. /**
  18043. * Parse animation range data from a serialization object and store them into a given node
  18044. * @param node defines where to store the animation ranges
  18045. * @param parsedNode defines the serialization object to read data from
  18046. * @param scene defines the hosting scene
  18047. */
  18048. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18049. if (parsedNode.ranges) {
  18050. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18051. var data = parsedNode.ranges[index];
  18052. node.createAnimationRange(data.name, data.from, data.to);
  18053. }
  18054. }
  18055. };
  18056. Node._NodeConstructors = {};
  18057. __decorate([
  18058. BABYLON.serialize()
  18059. ], Node.prototype, "name", void 0);
  18060. __decorate([
  18061. BABYLON.serialize()
  18062. ], Node.prototype, "id", void 0);
  18063. __decorate([
  18064. BABYLON.serialize()
  18065. ], Node.prototype, "uniqueId", void 0);
  18066. __decorate([
  18067. BABYLON.serialize()
  18068. ], Node.prototype, "state", void 0);
  18069. __decorate([
  18070. BABYLON.serialize()
  18071. ], Node.prototype, "metadata", void 0);
  18072. return Node;
  18073. }());
  18074. BABYLON.Node = Node;
  18075. })(BABYLON || (BABYLON = {}));
  18076. //# sourceMappingURL=babylon.node.js.map
  18077. var BABYLON;
  18078. (function (BABYLON) {
  18079. // This matrix is used as a value to reset the bounding box.
  18080. var _identityMatrix = BABYLON.Matrix.Identity();
  18081. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18082. var BoundingSphere = /** @class */ (function () {
  18083. /**
  18084. * Creates a new bounding sphere
  18085. * @param min defines the minimum vector (in local space)
  18086. * @param max defines the maximum vector (in local space)
  18087. */
  18088. function BoundingSphere(min, max) {
  18089. this.center = BABYLON.Vector3.Zero();
  18090. this.centerWorld = BABYLON.Vector3.Zero();
  18091. this.reConstruct(min, max);
  18092. }
  18093. /**
  18094. * Recreates the entire bounding sphere from scratch
  18095. * @param min defines the new minimum vector (in local space)
  18096. * @param max defines the new maximum vector (in local space)
  18097. */
  18098. BoundingSphere.prototype.reConstruct = function (min, max) {
  18099. this.minimum = min.clone();
  18100. this.maximum = max.clone();
  18101. var distance = BABYLON.Vector3.Distance(min, max);
  18102. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18103. this.radius = distance * 0.5;
  18104. this.centerWorld.set(0, 0, 0);
  18105. this._update(_identityMatrix);
  18106. };
  18107. /**
  18108. * Scale the current bounding sphere by applying a scale factor
  18109. * @param factor defines the scale factor to apply
  18110. * @returns the current bounding box
  18111. */
  18112. BoundingSphere.prototype.scale = function (factor) {
  18113. var newRadius = this.radius * factor;
  18114. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18115. var min = this.center.subtract(_tempRadiusVector);
  18116. var max = this.center.add(_tempRadiusVector);
  18117. this.reConstruct(min, max);
  18118. return this;
  18119. };
  18120. // Methods
  18121. /** @hidden */
  18122. BoundingSphere.prototype._update = function (world) {
  18123. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18124. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18125. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18126. };
  18127. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18128. for (var i = 0; i < 6; i++) {
  18129. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18130. return false;
  18131. }
  18132. return true;
  18133. };
  18134. BoundingSphere.prototype.intersectsPoint = function (point) {
  18135. var x = this.centerWorld.x - point.x;
  18136. var y = this.centerWorld.y - point.y;
  18137. var z = this.centerWorld.z - point.z;
  18138. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18139. if (this.radiusWorld < distance)
  18140. return false;
  18141. return true;
  18142. };
  18143. // Statics
  18144. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18145. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18146. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18147. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18148. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18149. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18150. return false;
  18151. return true;
  18152. };
  18153. return BoundingSphere;
  18154. }());
  18155. BABYLON.BoundingSphere = BoundingSphere;
  18156. })(BABYLON || (BABYLON = {}));
  18157. //# sourceMappingURL=babylon.boundingSphere.js.map
  18158. var BABYLON;
  18159. (function (BABYLON) {
  18160. var BoundingBox = /** @class */ (function () {
  18161. /**
  18162. * Creates a new bounding box
  18163. * @param min defines the minimum vector (in local space)
  18164. * @param max defines the maximum vector (in local space)
  18165. */
  18166. function BoundingBox(min, max) {
  18167. this.vectorsWorld = new Array();
  18168. this.reConstruct(min, max);
  18169. }
  18170. // Methods
  18171. /**
  18172. * Recreates the entire bounding box from scratch
  18173. * @param min defines the new minimum vector (in local space)
  18174. * @param max defines the new maximum vector (in local space)
  18175. */
  18176. BoundingBox.prototype.reConstruct = function (min, max) {
  18177. this.minimum = min.clone();
  18178. this.maximum = max.clone();
  18179. // Bounding vectors
  18180. this.vectors = [
  18181. this.minimum.clone(),
  18182. this.maximum.clone(),
  18183. this.minimum.clone(),
  18184. this.minimum.clone(),
  18185. this.minimum.clone(),
  18186. this.maximum.clone(),
  18187. this.maximum.clone(),
  18188. this.maximum.clone()
  18189. ];
  18190. this.vectors[2].x = this.maximum.x;
  18191. this.vectors[3].y = this.maximum.y;
  18192. this.vectors[4].z = this.maximum.z;
  18193. this.vectors[5].z = this.minimum.z;
  18194. this.vectors[6].x = this.minimum.x;
  18195. this.vectors[7].y = this.minimum.y;
  18196. // OBB
  18197. this.center = this.maximum.add(this.minimum).scale(0.5);
  18198. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18199. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18200. // World
  18201. for (var index = 0; index < this.vectors.length; index++) {
  18202. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18203. }
  18204. this.minimumWorld = BABYLON.Vector3.Zero();
  18205. this.maximumWorld = BABYLON.Vector3.Zero();
  18206. this.centerWorld = BABYLON.Vector3.Zero();
  18207. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18208. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18209. };
  18210. /**
  18211. * Scale the current bounding box by applying a scale factor
  18212. * @param factor defines the scale factor to apply
  18213. * @returns the current bounding box
  18214. */
  18215. BoundingBox.prototype.scale = function (factor) {
  18216. var diff = this.maximum.subtract(this.minimum);
  18217. var distance = diff.length() * factor;
  18218. diff.normalize();
  18219. var newRadius = diff.scale(distance / 2);
  18220. var min = this.center.subtract(newRadius);
  18221. var max = this.center.add(newRadius);
  18222. this.reConstruct(min, max);
  18223. return this;
  18224. };
  18225. BoundingBox.prototype.getWorldMatrix = function () {
  18226. return this._worldMatrix;
  18227. };
  18228. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18229. this._worldMatrix.copyFrom(matrix);
  18230. return this;
  18231. };
  18232. /** @hidden */
  18233. BoundingBox.prototype._update = function (world) {
  18234. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18235. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18236. for (var index = 0; index < this.vectors.length; index++) {
  18237. var v = this.vectorsWorld[index];
  18238. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18239. if (v.x < this.minimumWorld.x)
  18240. this.minimumWorld.x = v.x;
  18241. if (v.y < this.minimumWorld.y)
  18242. this.minimumWorld.y = v.y;
  18243. if (v.z < this.minimumWorld.z)
  18244. this.minimumWorld.z = v.z;
  18245. if (v.x > this.maximumWorld.x)
  18246. this.maximumWorld.x = v.x;
  18247. if (v.y > this.maximumWorld.y)
  18248. this.maximumWorld.y = v.y;
  18249. if (v.z > this.maximumWorld.z)
  18250. this.maximumWorld.z = v.z;
  18251. }
  18252. // Extend
  18253. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18254. this.extendSizeWorld.scaleInPlace(0.5);
  18255. // OBB
  18256. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18257. this.centerWorld.scaleInPlace(0.5);
  18258. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18259. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18260. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18261. this._worldMatrix = world;
  18262. };
  18263. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18264. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18265. };
  18266. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18267. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18268. };
  18269. BoundingBox.prototype.intersectsPoint = function (point) {
  18270. var delta = -BABYLON.Epsilon;
  18271. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18272. return false;
  18273. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18274. return false;
  18275. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18276. return false;
  18277. return true;
  18278. };
  18279. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18280. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18281. };
  18282. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18283. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18284. return false;
  18285. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18286. return false;
  18287. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18288. return false;
  18289. return true;
  18290. };
  18291. // Statics
  18292. BoundingBox.Intersects = function (box0, box1) {
  18293. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18294. return false;
  18295. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18296. return false;
  18297. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18298. return false;
  18299. return true;
  18300. };
  18301. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18302. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18303. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18304. return (num <= (sphereRadius * sphereRadius));
  18305. };
  18306. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18307. for (var p = 0; p < 6; p++) {
  18308. for (var i = 0; i < 8; i++) {
  18309. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18310. return false;
  18311. }
  18312. }
  18313. }
  18314. return true;
  18315. };
  18316. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18317. for (var p = 0; p < 6; p++) {
  18318. var inCount = 8;
  18319. for (var i = 0; i < 8; i++) {
  18320. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18321. --inCount;
  18322. }
  18323. else {
  18324. break;
  18325. }
  18326. }
  18327. if (inCount === 0)
  18328. return false;
  18329. }
  18330. return true;
  18331. };
  18332. return BoundingBox;
  18333. }());
  18334. BABYLON.BoundingBox = BoundingBox;
  18335. })(BABYLON || (BABYLON = {}));
  18336. //# sourceMappingURL=babylon.boundingBox.js.map
  18337. var BABYLON;
  18338. (function (BABYLON) {
  18339. var computeBoxExtents = function (axis, box) {
  18340. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18341. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18342. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18343. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18344. var r = r0 + r1 + r2;
  18345. return {
  18346. min: p - r,
  18347. max: p + r
  18348. };
  18349. };
  18350. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18351. var axisOverlap = function (axis, box0, box1) {
  18352. var result0 = computeBoxExtents(axis, box0);
  18353. var result1 = computeBoxExtents(axis, box1);
  18354. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18355. };
  18356. var BoundingInfo = /** @class */ (function () {
  18357. function BoundingInfo(minimum, maximum) {
  18358. this.minimum = minimum;
  18359. this.maximum = maximum;
  18360. this._isLocked = false;
  18361. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18362. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18363. }
  18364. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18365. get: function () {
  18366. return this._isLocked;
  18367. },
  18368. set: function (value) {
  18369. this._isLocked = value;
  18370. },
  18371. enumerable: true,
  18372. configurable: true
  18373. });
  18374. // Methods
  18375. BoundingInfo.prototype.update = function (world) {
  18376. if (this._isLocked) {
  18377. return;
  18378. }
  18379. this.boundingBox._update(world);
  18380. this.boundingSphere._update(world);
  18381. };
  18382. /**
  18383. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18384. * @param center New center of the bounding info
  18385. * @param extend New extend of the bounding info
  18386. */
  18387. BoundingInfo.prototype.centerOn = function (center, extend) {
  18388. this.minimum = center.subtract(extend);
  18389. this.maximum = center.add(extend);
  18390. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18391. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18392. return this;
  18393. };
  18394. /**
  18395. * Scale the current bounding info by applying a scale factor
  18396. * @param factor defines the scale factor to apply
  18397. * @returns the current bounding info
  18398. */
  18399. BoundingInfo.prototype.scale = function (factor) {
  18400. this.boundingBox.scale(factor);
  18401. this.boundingSphere.scale(factor);
  18402. return this;
  18403. };
  18404. /**
  18405. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18406. * @param frustumPlanes defines the frustum to test
  18407. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18408. * @returns true if the bounding info is in the frustum planes
  18409. */
  18410. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18411. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18412. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18413. return false;
  18414. }
  18415. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18416. return true;
  18417. }
  18418. return this.boundingBox.isInFrustum(frustumPlanes);
  18419. };
  18420. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18421. /**
  18422. * Gets the world distance between the min and max points of the bounding box
  18423. */
  18424. get: function () {
  18425. var boundingBox = this.boundingBox;
  18426. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18427. return size.length();
  18428. },
  18429. enumerable: true,
  18430. configurable: true
  18431. });
  18432. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18433. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18434. };
  18435. /** @hidden */
  18436. BoundingInfo.prototype._checkCollision = function (collider) {
  18437. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18438. };
  18439. BoundingInfo.prototype.intersectsPoint = function (point) {
  18440. if (!this.boundingSphere.centerWorld) {
  18441. return false;
  18442. }
  18443. if (!this.boundingSphere.intersectsPoint(point)) {
  18444. return false;
  18445. }
  18446. if (!this.boundingBox.intersectsPoint(point)) {
  18447. return false;
  18448. }
  18449. return true;
  18450. };
  18451. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18452. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18453. return false;
  18454. }
  18455. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18456. return false;
  18457. }
  18458. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18459. return false;
  18460. }
  18461. if (!precise) {
  18462. return true;
  18463. }
  18464. var box0 = this.boundingBox;
  18465. var box1 = boundingInfo.boundingBox;
  18466. if (!axisOverlap(box0.directions[0], box0, box1))
  18467. return false;
  18468. if (!axisOverlap(box0.directions[1], box0, box1))
  18469. return false;
  18470. if (!axisOverlap(box0.directions[2], box0, box1))
  18471. return false;
  18472. if (!axisOverlap(box1.directions[0], box0, box1))
  18473. return false;
  18474. if (!axisOverlap(box1.directions[1], box0, box1))
  18475. return false;
  18476. if (!axisOverlap(box1.directions[2], box0, box1))
  18477. return false;
  18478. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18479. return false;
  18480. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18481. return false;
  18482. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18483. return false;
  18484. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18485. return false;
  18486. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18487. return false;
  18488. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18489. return false;
  18490. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18491. return false;
  18492. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18493. return false;
  18494. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18495. return false;
  18496. return true;
  18497. };
  18498. return BoundingInfo;
  18499. }());
  18500. BABYLON.BoundingInfo = BoundingInfo;
  18501. })(BABYLON || (BABYLON = {}));
  18502. //# sourceMappingURL=babylon.boundingInfo.js.map
  18503. var BABYLON;
  18504. (function (BABYLON) {
  18505. var TransformNode = /** @class */ (function (_super) {
  18506. __extends(TransformNode, _super);
  18507. function TransformNode(name, scene, isPure) {
  18508. if (scene === void 0) { scene = null; }
  18509. if (isPure === void 0) { isPure = true; }
  18510. var _this = _super.call(this, name, scene) || this;
  18511. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18512. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18513. _this._up = new BABYLON.Vector3(0, 1, 0);
  18514. _this._right = new BABYLON.Vector3(1, 0, 0);
  18515. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18516. // Properties
  18517. _this._rotation = BABYLON.Vector3.Zero();
  18518. _this._scaling = BABYLON.Vector3.One();
  18519. _this._isDirty = false;
  18520. /**
  18521. * Set the billboard mode. Default is 0.
  18522. *
  18523. * | Value | Type | Description |
  18524. * | --- | --- | --- |
  18525. * | 0 | BILLBOARDMODE_NONE | |
  18526. * | 1 | BILLBOARDMODE_X | |
  18527. * | 2 | BILLBOARDMODE_Y | |
  18528. * | 4 | BILLBOARDMODE_Z | |
  18529. * | 7 | BILLBOARDMODE_ALL | |
  18530. *
  18531. */
  18532. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18533. _this.scalingDeterminant = 1;
  18534. _this.infiniteDistance = false;
  18535. /**
  18536. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18537. * By default the system will update normals to compensate
  18538. */
  18539. _this.ignoreNonUniformScaling = false;
  18540. _this.position = BABYLON.Vector3.Zero();
  18541. _this._localWorld = BABYLON.Matrix.Zero();
  18542. /** @hidden */
  18543. _this._worldMatrix = BABYLON.Matrix.Zero();
  18544. /** @hidden */
  18545. _this._worldMatrixDeterminant = 0;
  18546. _this._absolutePosition = BABYLON.Vector3.Zero();
  18547. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18548. _this._postMultiplyPivotMatrix = false;
  18549. _this._isWorldMatrixFrozen = false;
  18550. /**
  18551. * An event triggered after the world matrix is updated
  18552. */
  18553. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18554. _this._nonUniformScaling = false;
  18555. if (isPure) {
  18556. _this.getScene().addTransformNode(_this);
  18557. }
  18558. return _this;
  18559. }
  18560. /**
  18561. * Gets a string identifying the name of the class
  18562. * @returns "TransformNode" string
  18563. */
  18564. TransformNode.prototype.getClassName = function () {
  18565. return "TransformNode";
  18566. };
  18567. Object.defineProperty(TransformNode.prototype, "rotation", {
  18568. /**
  18569. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18570. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18571. * Default : (0.0, 0.0, 0.0)
  18572. */
  18573. get: function () {
  18574. return this._rotation;
  18575. },
  18576. set: function (newRotation) {
  18577. this._rotation = newRotation;
  18578. },
  18579. enumerable: true,
  18580. configurable: true
  18581. });
  18582. Object.defineProperty(TransformNode.prototype, "scaling", {
  18583. /**
  18584. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18585. * Default : (1.0, 1.0, 1.0)
  18586. */
  18587. get: function () {
  18588. return this._scaling;
  18589. },
  18590. /**
  18591. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18592. * Default : (1.0, 1.0, 1.0)
  18593. */
  18594. set: function (newScaling) {
  18595. this._scaling = newScaling;
  18596. },
  18597. enumerable: true,
  18598. configurable: true
  18599. });
  18600. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18601. /**
  18602. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18603. * It's null by default.
  18604. * 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)
  18605. */
  18606. get: function () {
  18607. return this._rotationQuaternion;
  18608. },
  18609. set: function (quaternion) {
  18610. this._rotationQuaternion = quaternion;
  18611. //reset the rotation vector.
  18612. if (quaternion && this.rotation.length()) {
  18613. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18614. }
  18615. },
  18616. enumerable: true,
  18617. configurable: true
  18618. });
  18619. Object.defineProperty(TransformNode.prototype, "forward", {
  18620. /**
  18621. * The forward direction of that transform in world space.
  18622. */
  18623. get: function () {
  18624. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18625. },
  18626. enumerable: true,
  18627. configurable: true
  18628. });
  18629. Object.defineProperty(TransformNode.prototype, "up", {
  18630. /**
  18631. * The up direction of that transform in world space.
  18632. */
  18633. get: function () {
  18634. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18635. },
  18636. enumerable: true,
  18637. configurable: true
  18638. });
  18639. Object.defineProperty(TransformNode.prototype, "right", {
  18640. /**
  18641. * The right direction of that transform in world space.
  18642. */
  18643. get: function () {
  18644. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18645. },
  18646. enumerable: true,
  18647. configurable: true
  18648. });
  18649. /**
  18650. * Returns the latest update of the World matrix
  18651. * Returns a Matrix.
  18652. */
  18653. TransformNode.prototype.getWorldMatrix = function () {
  18654. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18655. this.computeWorldMatrix();
  18656. }
  18657. return this._worldMatrix;
  18658. };
  18659. /** @hidden */
  18660. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18661. return this._worldMatrixDeterminant;
  18662. };
  18663. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18664. /**
  18665. * Returns directly the latest state of the mesh World matrix.
  18666. * A Matrix is returned.
  18667. */
  18668. get: function () {
  18669. return this._worldMatrix;
  18670. },
  18671. enumerable: true,
  18672. configurable: true
  18673. });
  18674. /**
  18675. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18676. * Returns the TransformNode.
  18677. */
  18678. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18679. this._poseMatrix.copyFrom(matrix);
  18680. return this;
  18681. };
  18682. /**
  18683. * Returns the mesh Pose matrix.
  18684. * Returned object : Matrix
  18685. */
  18686. TransformNode.prototype.getPoseMatrix = function () {
  18687. return this._poseMatrix;
  18688. };
  18689. /** @hidden */
  18690. TransformNode.prototype._isSynchronized = function () {
  18691. if (this._isDirty) {
  18692. return false;
  18693. }
  18694. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18695. return false;
  18696. if (this._cache.pivotMatrixUpdated) {
  18697. return false;
  18698. }
  18699. if (this.infiniteDistance) {
  18700. return false;
  18701. }
  18702. if (!this._cache.position.equals(this.position))
  18703. return false;
  18704. if (this._rotationQuaternion) {
  18705. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  18706. return false;
  18707. }
  18708. if (!this._cache.rotation.equals(this.rotation))
  18709. return false;
  18710. if (!this._cache.scaling.equals(this.scaling))
  18711. return false;
  18712. return true;
  18713. };
  18714. /** @hidden */
  18715. TransformNode.prototype._initCache = function () {
  18716. _super.prototype._initCache.call(this);
  18717. this._cache.localMatrixUpdated = false;
  18718. this._cache.position = BABYLON.Vector3.Zero();
  18719. this._cache.scaling = BABYLON.Vector3.Zero();
  18720. this._cache.rotation = BABYLON.Vector3.Zero();
  18721. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18722. this._cache.billboardMode = -1;
  18723. };
  18724. TransformNode.prototype.markAsDirty = function (property) {
  18725. if (property === "rotation") {
  18726. this.rotationQuaternion = null;
  18727. }
  18728. this._currentRenderId = Number.MAX_VALUE;
  18729. this._isDirty = true;
  18730. return this;
  18731. };
  18732. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18733. /**
  18734. * Returns the current mesh absolute position.
  18735. * Returns a Vector3.
  18736. */
  18737. get: function () {
  18738. return this._absolutePosition;
  18739. },
  18740. enumerable: true,
  18741. configurable: true
  18742. });
  18743. /**
  18744. * Sets a new matrix to apply before all other transformation
  18745. * @param matrix defines the transform matrix
  18746. * @returns the current TransformNode
  18747. */
  18748. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18749. return this.setPivotMatrix(matrix, false);
  18750. };
  18751. /**
  18752. * Sets a new pivot matrix to the current node
  18753. * @param matrix defines the new pivot matrix to use
  18754. * @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
  18755. * @returns the current TransformNode
  18756. */
  18757. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18758. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18759. this._pivotMatrix = matrix.clone();
  18760. this._cache.pivotMatrixUpdated = true;
  18761. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18762. if (this._postMultiplyPivotMatrix) {
  18763. if (!this._pivotMatrixInverse) {
  18764. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18765. }
  18766. else {
  18767. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18768. }
  18769. }
  18770. return this;
  18771. };
  18772. /**
  18773. * Returns the mesh pivot matrix.
  18774. * Default : Identity.
  18775. * A Matrix is returned.
  18776. */
  18777. TransformNode.prototype.getPivotMatrix = function () {
  18778. return this._pivotMatrix;
  18779. };
  18780. /**
  18781. * Prevents the World matrix to be computed any longer.
  18782. * Returns the TransformNode.
  18783. */
  18784. TransformNode.prototype.freezeWorldMatrix = function () {
  18785. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18786. this.computeWorldMatrix(true);
  18787. this._isWorldMatrixFrozen = true;
  18788. return this;
  18789. };
  18790. /**
  18791. * Allows back the World matrix computation.
  18792. * Returns the TransformNode.
  18793. */
  18794. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18795. this._isWorldMatrixFrozen = false;
  18796. this.computeWorldMatrix(true);
  18797. return this;
  18798. };
  18799. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18800. /**
  18801. * True if the World matrix has been frozen.
  18802. * Returns a boolean.
  18803. */
  18804. get: function () {
  18805. return this._isWorldMatrixFrozen;
  18806. },
  18807. enumerable: true,
  18808. configurable: true
  18809. });
  18810. /**
  18811. * Retuns the mesh absolute position in the World.
  18812. * Returns a Vector3.
  18813. */
  18814. TransformNode.prototype.getAbsolutePosition = function () {
  18815. this.computeWorldMatrix();
  18816. return this._absolutePosition;
  18817. };
  18818. /**
  18819. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18820. * Returns the TransformNode.
  18821. */
  18822. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18823. if (!absolutePosition) {
  18824. return this;
  18825. }
  18826. var absolutePositionX;
  18827. var absolutePositionY;
  18828. var absolutePositionZ;
  18829. if (absolutePosition.x === undefined) {
  18830. if (arguments.length < 3) {
  18831. return this;
  18832. }
  18833. absolutePositionX = arguments[0];
  18834. absolutePositionY = arguments[1];
  18835. absolutePositionZ = arguments[2];
  18836. }
  18837. else {
  18838. absolutePositionX = absolutePosition.x;
  18839. absolutePositionY = absolutePosition.y;
  18840. absolutePositionZ = absolutePosition.z;
  18841. }
  18842. if (this.parent) {
  18843. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18844. invertParentWorldMatrix.invert();
  18845. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18846. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18847. }
  18848. else {
  18849. this.position.x = absolutePositionX;
  18850. this.position.y = absolutePositionY;
  18851. this.position.z = absolutePositionZ;
  18852. }
  18853. return this;
  18854. };
  18855. /**
  18856. * Sets the mesh position in its local space.
  18857. * Returns the TransformNode.
  18858. */
  18859. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18860. this.computeWorldMatrix();
  18861. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18862. return this;
  18863. };
  18864. /**
  18865. * Returns the mesh position in the local space from the current World matrix values.
  18866. * Returns a new Vector3.
  18867. */
  18868. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18869. this.computeWorldMatrix();
  18870. var invLocalWorldMatrix = this._localWorld.clone();
  18871. invLocalWorldMatrix.invert();
  18872. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18873. };
  18874. /**
  18875. * Translates the mesh along the passed Vector3 in its local space.
  18876. * Returns the TransformNode.
  18877. */
  18878. TransformNode.prototype.locallyTranslate = function (vector3) {
  18879. this.computeWorldMatrix(true);
  18880. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18881. return this;
  18882. };
  18883. /**
  18884. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18885. * @param targetPoint the position (must be in same space as current mesh) to look at
  18886. * @param yawCor optional yaw (y-axis) correction in radians
  18887. * @param pitchCor optional pitch (x-axis) correction in radians
  18888. * @param rollCor optional roll (z-axis) correction in radians
  18889. * @param space the choosen space of the target
  18890. * @returns the TransformNode.
  18891. */
  18892. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18893. if (yawCor === void 0) { yawCor = 0; }
  18894. if (pitchCor === void 0) { pitchCor = 0; }
  18895. if (rollCor === void 0) { rollCor = 0; }
  18896. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18897. var dv = TransformNode._lookAtVectorCache;
  18898. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18899. targetPoint.subtractToRef(pos, dv);
  18900. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18901. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18902. var pitch = Math.atan2(dv.y, len);
  18903. if (this.rotationQuaternion) {
  18904. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18905. }
  18906. else {
  18907. this.rotation.x = pitch + pitchCor;
  18908. this.rotation.y = yaw + yawCor;
  18909. this.rotation.z = rollCor;
  18910. }
  18911. return this;
  18912. };
  18913. /**
  18914. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18915. * This Vector3 is expressed in the World space.
  18916. */
  18917. TransformNode.prototype.getDirection = function (localAxis) {
  18918. var result = BABYLON.Vector3.Zero();
  18919. this.getDirectionToRef(localAxis, result);
  18920. return result;
  18921. };
  18922. /**
  18923. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18924. * localAxis is expressed in the mesh local space.
  18925. * result is computed in the Wordl space from the mesh World matrix.
  18926. * Returns the TransformNode.
  18927. */
  18928. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18929. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18930. return this;
  18931. };
  18932. /**
  18933. * Sets a new pivot point to the current node
  18934. * @param point defines the new pivot point to use
  18935. * @param space defines if the point is in world or local space (local by default)
  18936. * @returns the current TransformNode
  18937. */
  18938. TransformNode.prototype.setPivotPoint = function (point, space) {
  18939. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18940. if (this.getScene().getRenderId() == 0) {
  18941. this.computeWorldMatrix(true);
  18942. }
  18943. var wm = this.getWorldMatrix();
  18944. if (space == BABYLON.Space.WORLD) {
  18945. var tmat = BABYLON.Tmp.Matrix[0];
  18946. wm.invertToRef(tmat);
  18947. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18948. }
  18949. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18950. };
  18951. /**
  18952. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18953. */
  18954. TransformNode.prototype.getPivotPoint = function () {
  18955. var point = BABYLON.Vector3.Zero();
  18956. this.getPivotPointToRef(point);
  18957. return point;
  18958. };
  18959. /**
  18960. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18961. * Returns the TransformNode.
  18962. */
  18963. TransformNode.prototype.getPivotPointToRef = function (result) {
  18964. result.x = -this._pivotMatrix.m[12];
  18965. result.y = -this._pivotMatrix.m[13];
  18966. result.z = -this._pivotMatrix.m[14];
  18967. return this;
  18968. };
  18969. /**
  18970. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18971. */
  18972. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18973. var point = BABYLON.Vector3.Zero();
  18974. this.getAbsolutePivotPointToRef(point);
  18975. return point;
  18976. };
  18977. /**
  18978. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18979. * Returns the TransformNode.
  18980. */
  18981. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18982. result.x = this._pivotMatrix.m[12];
  18983. result.y = this._pivotMatrix.m[13];
  18984. result.z = this._pivotMatrix.m[14];
  18985. this.getPivotPointToRef(result);
  18986. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18987. return this;
  18988. };
  18989. /**
  18990. * Defines the passed node as the parent of the current node.
  18991. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18992. * Returns the TransformNode.
  18993. */
  18994. TransformNode.prototype.setParent = function (node) {
  18995. if (!node && !this.parent) {
  18996. return this;
  18997. }
  18998. if (!node) {
  18999. var rotation = BABYLON.Tmp.Quaternion[0];
  19000. var position = BABYLON.Tmp.Vector3[0];
  19001. var scale = BABYLON.Tmp.Vector3[1];
  19002. if (this.parent && this.parent.computeWorldMatrix) {
  19003. this.parent.computeWorldMatrix(true);
  19004. }
  19005. this.computeWorldMatrix(true);
  19006. this.getWorldMatrix().decompose(scale, rotation, position);
  19007. if (this.rotationQuaternion) {
  19008. this.rotationQuaternion.copyFrom(rotation);
  19009. }
  19010. else {
  19011. rotation.toEulerAnglesToRef(this.rotation);
  19012. }
  19013. this.scaling.x = scale.x;
  19014. this.scaling.y = scale.y;
  19015. this.scaling.z = scale.z;
  19016. this.position.x = position.x;
  19017. this.position.y = position.y;
  19018. this.position.z = position.z;
  19019. }
  19020. else {
  19021. var rotation = BABYLON.Tmp.Quaternion[0];
  19022. var position = BABYLON.Tmp.Vector3[0];
  19023. var scale = BABYLON.Tmp.Vector3[1];
  19024. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19025. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19026. this.computeWorldMatrix(true);
  19027. node.computeWorldMatrix(true);
  19028. node.getWorldMatrix().invertToRef(invParentMatrix);
  19029. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19030. diffMatrix.decompose(scale, rotation, position);
  19031. if (this.rotationQuaternion) {
  19032. this.rotationQuaternion.copyFrom(rotation);
  19033. }
  19034. else {
  19035. rotation.toEulerAnglesToRef(this.rotation);
  19036. }
  19037. this.position.x = position.x;
  19038. this.position.y = position.y;
  19039. this.position.z = position.z;
  19040. this.scaling.x = scale.x;
  19041. this.scaling.y = scale.y;
  19042. this.scaling.z = scale.z;
  19043. }
  19044. this.parent = node;
  19045. return this;
  19046. };
  19047. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19048. get: function () {
  19049. return this._nonUniformScaling;
  19050. },
  19051. enumerable: true,
  19052. configurable: true
  19053. });
  19054. /** @hidden */
  19055. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19056. if (this._nonUniformScaling === value) {
  19057. return false;
  19058. }
  19059. this._nonUniformScaling = value;
  19060. return true;
  19061. };
  19062. /**
  19063. * Attach the current TransformNode to another TransformNode associated with a bone
  19064. * @param bone Bone affecting the TransformNode
  19065. * @param affectedTransformNode TransformNode associated with the bone
  19066. */
  19067. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19068. this._transformToBoneReferal = affectedTransformNode;
  19069. this.parent = bone;
  19070. if (bone.getWorldMatrix().determinant() < 0) {
  19071. this.scalingDeterminant *= -1;
  19072. }
  19073. return this;
  19074. };
  19075. TransformNode.prototype.detachFromBone = function () {
  19076. if (!this.parent) {
  19077. return this;
  19078. }
  19079. if (this.parent.getWorldMatrix().determinant() < 0) {
  19080. this.scalingDeterminant *= -1;
  19081. }
  19082. this._transformToBoneReferal = null;
  19083. this.parent = null;
  19084. return this;
  19085. };
  19086. /**
  19087. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19088. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19089. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19090. * The passed axis is also normalized.
  19091. * Returns the TransformNode.
  19092. */
  19093. TransformNode.prototype.rotate = function (axis, amount, space) {
  19094. axis.normalize();
  19095. if (!this.rotationQuaternion) {
  19096. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19097. this.rotation = BABYLON.Vector3.Zero();
  19098. }
  19099. var rotationQuaternion;
  19100. if (!space || space === BABYLON.Space.LOCAL) {
  19101. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19102. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19103. }
  19104. else {
  19105. if (this.parent) {
  19106. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19107. invertParentWorldMatrix.invert();
  19108. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19109. }
  19110. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19111. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19112. }
  19113. return this;
  19114. };
  19115. /**
  19116. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19117. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19118. * The passed axis is also normalized.
  19119. * Returns the TransformNode.
  19120. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19121. */
  19122. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19123. axis.normalize();
  19124. if (!this.rotationQuaternion) {
  19125. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19126. this.rotation.copyFromFloats(0, 0, 0);
  19127. }
  19128. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19129. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19130. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19131. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19132. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19133. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19134. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19135. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19136. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19137. return this;
  19138. };
  19139. /**
  19140. * Translates the mesh along the axis vector for the passed distance in the given space.
  19141. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19142. * Returns the TransformNode.
  19143. */
  19144. TransformNode.prototype.translate = function (axis, distance, space) {
  19145. var displacementVector = axis.scale(distance);
  19146. if (!space || space === BABYLON.Space.LOCAL) {
  19147. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19148. this.setPositionWithLocalVector(tempV3);
  19149. }
  19150. else {
  19151. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19152. }
  19153. return this;
  19154. };
  19155. /**
  19156. * Adds a rotation step to the mesh current rotation.
  19157. * x, y, z are Euler angles expressed in radians.
  19158. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19159. * This means this rotation is made in the mesh local space only.
  19160. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19161. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19162. * ```javascript
  19163. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19164. * ```
  19165. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19166. * 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.
  19167. * Returns the TransformNode.
  19168. */
  19169. TransformNode.prototype.addRotation = function (x, y, z) {
  19170. var rotationQuaternion;
  19171. if (this.rotationQuaternion) {
  19172. rotationQuaternion = this.rotationQuaternion;
  19173. }
  19174. else {
  19175. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19176. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19177. }
  19178. var accumulation = BABYLON.Tmp.Quaternion[0];
  19179. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19180. rotationQuaternion.multiplyInPlace(accumulation);
  19181. if (!this.rotationQuaternion) {
  19182. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19183. }
  19184. return this;
  19185. };
  19186. /**
  19187. * Computes the mesh World matrix and returns it.
  19188. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19189. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19190. * If the parameter `force`is set to `true`, the actual computation is done.
  19191. * Returns the mesh World Matrix.
  19192. */
  19193. TransformNode.prototype.computeWorldMatrix = function (force) {
  19194. if (this._isWorldMatrixFrozen) {
  19195. return this._worldMatrix;
  19196. }
  19197. if (!force && this.isSynchronized(true)) {
  19198. this._currentRenderId = this.getScene().getRenderId();
  19199. return this._worldMatrix;
  19200. }
  19201. this._cache.position.copyFrom(this.position);
  19202. this._cache.scaling.copyFrom(this.scaling);
  19203. this._cache.pivotMatrixUpdated = false;
  19204. this._cache.billboardMode = this.billboardMode;
  19205. this._currentRenderId = this.getScene().getRenderId();
  19206. this._childRenderId = this.getScene().getRenderId();
  19207. this._isDirty = false;
  19208. // Scaling
  19209. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19210. // Rotation
  19211. //rotate, if quaternion is set and rotation was used
  19212. if (this.rotationQuaternion) {
  19213. var len = this.rotation.length();
  19214. if (len) {
  19215. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19216. this.rotation.copyFromFloats(0, 0, 0);
  19217. }
  19218. }
  19219. if (this.rotationQuaternion) {
  19220. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19221. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19222. }
  19223. else {
  19224. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19225. this._cache.rotation.copyFrom(this.rotation);
  19226. }
  19227. // Translation
  19228. var camera = this.getScene().activeCamera;
  19229. if (this.infiniteDistance && !this.parent && camera) {
  19230. var cameraWorldMatrix = camera.getWorldMatrix();
  19231. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19232. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19233. }
  19234. else {
  19235. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19236. }
  19237. // Composing transformations
  19238. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19239. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19240. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19241. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19242. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19243. // Need to decompose each rotation here
  19244. var currentPosition = BABYLON.Tmp.Vector3[3];
  19245. if (this.parent && this.parent.getWorldMatrix) {
  19246. if (this._transformToBoneReferal) {
  19247. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19248. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19249. }
  19250. else {
  19251. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19252. }
  19253. }
  19254. else {
  19255. currentPosition.copyFrom(this.position);
  19256. }
  19257. currentPosition.subtractInPlace(camera.globalPosition);
  19258. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19259. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19260. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19261. }
  19262. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19263. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19264. }
  19265. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19266. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19267. }
  19268. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19269. }
  19270. else {
  19271. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19272. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19273. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19274. }
  19275. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19276. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19277. }
  19278. // Post multiply inverse of pivotMatrix
  19279. if (this._postMultiplyPivotMatrix) {
  19280. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19281. }
  19282. // Local world
  19283. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19284. // Parent
  19285. if (this.parent && this.parent.getWorldMatrix) {
  19286. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19287. if (this._transformToBoneReferal) {
  19288. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19289. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19290. }
  19291. else {
  19292. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19293. }
  19294. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19295. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19296. this._worldMatrix.copyFrom(this._localWorld);
  19297. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19298. }
  19299. else {
  19300. if (this._transformToBoneReferal) {
  19301. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19302. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19303. }
  19304. else {
  19305. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19306. }
  19307. }
  19308. this._markSyncedWithParent();
  19309. }
  19310. else {
  19311. this._worldMatrix.copyFrom(this._localWorld);
  19312. }
  19313. // Normal matrix
  19314. if (!this.ignoreNonUniformScaling) {
  19315. if (this.scaling.isNonUniform) {
  19316. this._updateNonUniformScalingState(true);
  19317. }
  19318. else if (this.parent && this.parent._nonUniformScaling) {
  19319. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19320. }
  19321. else {
  19322. this._updateNonUniformScalingState(false);
  19323. }
  19324. }
  19325. else {
  19326. this._updateNonUniformScalingState(false);
  19327. }
  19328. this._afterComputeWorldMatrix();
  19329. // Absolute position
  19330. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19331. // Callbacks
  19332. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19333. if (!this._poseMatrix) {
  19334. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19335. }
  19336. // Cache the determinant
  19337. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19338. return this._worldMatrix;
  19339. };
  19340. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19341. };
  19342. /**
  19343. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19344. * @param func: callback function to add
  19345. *
  19346. * Returns the TransformNode.
  19347. */
  19348. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19349. this.onAfterWorldMatrixUpdateObservable.add(func);
  19350. return this;
  19351. };
  19352. /**
  19353. * Removes a registered callback function.
  19354. * Returns the TransformNode.
  19355. */
  19356. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19357. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19358. return this;
  19359. };
  19360. /**
  19361. * Clone the current transform node
  19362. * Returns the new transform node
  19363. * @param name Name of the new clone
  19364. * @param newParent New parent for the clone
  19365. * @param doNotCloneChildren Do not clone children hierarchy
  19366. */
  19367. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19368. var _this = this;
  19369. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19370. result.name = name;
  19371. result.id = name;
  19372. if (newParent) {
  19373. result.parent = newParent;
  19374. }
  19375. if (!doNotCloneChildren) {
  19376. // Children
  19377. var directDescendants = this.getDescendants(true);
  19378. for (var index = 0; index < directDescendants.length; index++) {
  19379. var child = directDescendants[index];
  19380. if (child.clone) {
  19381. child.clone(name + "." + child.name, result);
  19382. }
  19383. }
  19384. }
  19385. return result;
  19386. };
  19387. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19388. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19389. serializationObject.type = this.getClassName();
  19390. // Parent
  19391. if (this.parent) {
  19392. serializationObject.parentId = this.parent.id;
  19393. }
  19394. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19395. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19396. }
  19397. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19398. serializationObject.isEnabled = this.isEnabled();
  19399. // Parent
  19400. if (this.parent) {
  19401. serializationObject.parentId = this.parent.id;
  19402. }
  19403. return serializationObject;
  19404. };
  19405. // Statics
  19406. /**
  19407. * Returns a new TransformNode object parsed from the source provided.
  19408. * The parameter `parsedMesh` is the source.
  19409. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19410. */
  19411. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19412. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19413. if (BABYLON.Tags) {
  19414. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19415. }
  19416. if (parsedTransformNode.localMatrix) {
  19417. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19418. }
  19419. else if (parsedTransformNode.pivotMatrix) {
  19420. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19421. }
  19422. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19423. // Parent
  19424. if (parsedTransformNode.parentId) {
  19425. transformNode._waitingParentId = parsedTransformNode.parentId;
  19426. }
  19427. return transformNode;
  19428. };
  19429. /**
  19430. * Releases resources associated with this transform node.
  19431. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19432. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19433. */
  19434. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19435. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19436. // Animations
  19437. this.getScene().stopAnimation(this);
  19438. // Remove from scene
  19439. this.getScene().removeTransformNode(this);
  19440. this.onAfterWorldMatrixUpdateObservable.clear();
  19441. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19442. };
  19443. // Statics
  19444. TransformNode.BILLBOARDMODE_NONE = 0;
  19445. TransformNode.BILLBOARDMODE_X = 1;
  19446. TransformNode.BILLBOARDMODE_Y = 2;
  19447. TransformNode.BILLBOARDMODE_Z = 4;
  19448. TransformNode.BILLBOARDMODE_ALL = 7;
  19449. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19450. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19451. __decorate([
  19452. BABYLON.serializeAsVector3()
  19453. ], TransformNode.prototype, "_rotation", void 0);
  19454. __decorate([
  19455. BABYLON.serializeAsQuaternion()
  19456. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19457. __decorate([
  19458. BABYLON.serializeAsVector3()
  19459. ], TransformNode.prototype, "_scaling", void 0);
  19460. __decorate([
  19461. BABYLON.serialize()
  19462. ], TransformNode.prototype, "billboardMode", void 0);
  19463. __decorate([
  19464. BABYLON.serialize()
  19465. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19466. __decorate([
  19467. BABYLON.serialize()
  19468. ], TransformNode.prototype, "infiniteDistance", void 0);
  19469. __decorate([
  19470. BABYLON.serialize()
  19471. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19472. __decorate([
  19473. BABYLON.serializeAsVector3()
  19474. ], TransformNode.prototype, "position", void 0);
  19475. return TransformNode;
  19476. }(BABYLON.Node));
  19477. BABYLON.TransformNode = TransformNode;
  19478. })(BABYLON || (BABYLON = {}));
  19479. //# sourceMappingURL=babylon.transformNode.js.map
  19480. var BABYLON;
  19481. (function (BABYLON) {
  19482. /**
  19483. * Class used to store all common mesh properties
  19484. */
  19485. var AbstractMesh = /** @class */ (function (_super) {
  19486. __extends(AbstractMesh, _super);
  19487. // Constructor
  19488. /**
  19489. * Creates a new AbstractMesh
  19490. * @param name defines the name of the mesh
  19491. * @param scene defines the hosting scene
  19492. */
  19493. function AbstractMesh(name, scene) {
  19494. if (scene === void 0) { scene = null; }
  19495. var _this = _super.call(this, name, scene, false) || this;
  19496. _this._facetNb = 0; // facet number
  19497. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19498. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19499. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19500. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19501. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19502. _this._subDiv = {
  19503. max: 1,
  19504. X: 1,
  19505. Y: 1,
  19506. Z: 1
  19507. };
  19508. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19509. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19510. /** Gets ot sets the culling strategy to use to find visible meshes */
  19511. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  19512. // Events
  19513. /**
  19514. * An event triggered when this mesh collides with another one
  19515. */
  19516. _this.onCollideObservable = new BABYLON.Observable();
  19517. /**
  19518. * An event triggered when the collision's position changes
  19519. */
  19520. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19521. /**
  19522. * An event triggered when material is changed
  19523. */
  19524. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19525. // Properties
  19526. /**
  19527. * Gets or sets the orientation for POV movement & rotation
  19528. */
  19529. _this.definedFacingForward = true;
  19530. /**
  19531. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19532. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19533. * * 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.
  19534. * @see http://doc.babylonjs.com/features/occlusionquery
  19535. */
  19536. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19537. /**
  19538. * 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:
  19539. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19540. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19541. * * 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.
  19542. * @see http://doc.babylonjs.com/features/occlusionquery
  19543. */
  19544. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19545. /**
  19546. * 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.
  19547. * The default value is -1 which means don't break the query and wait till the result
  19548. * @see http://doc.babylonjs.com/features/occlusionquery
  19549. */
  19550. _this.occlusionRetryCount = -1;
  19551. /** @hidden */
  19552. _this._occlusionInternalRetryCounter = 0;
  19553. /** @hidden */
  19554. _this._isOccluded = false;
  19555. /** @hidden */
  19556. _this._isOcclusionQueryInProgress = false;
  19557. _this._visibility = 1.0;
  19558. /** Gets or sets the alpha index used to sort transparent meshes
  19559. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19560. */
  19561. _this.alphaIndex = Number.MAX_VALUE;
  19562. /**
  19563. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19564. */
  19565. _this.isVisible = true;
  19566. /**
  19567. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19568. */
  19569. _this.isPickable = true;
  19570. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19571. _this.showSubMeshesBoundingBox = false;
  19572. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19573. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19574. */
  19575. _this.isBlocker = false;
  19576. /**
  19577. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19578. */
  19579. _this.enablePointerMoveEvents = false;
  19580. /**
  19581. * Specifies the rendering group id for this mesh (0 by default)
  19582. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19583. */
  19584. _this.renderingGroupId = 0;
  19585. _this._receiveShadows = false;
  19586. /**
  19587. * Gets or sets a boolean indicating if the outline must be rendered as well
  19588. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19589. */
  19590. _this.renderOutline = false;
  19591. /** Defines color to use when rendering outline */
  19592. _this.outlineColor = BABYLON.Color3.Red();
  19593. /** Define width to use when rendering outline */
  19594. _this.outlineWidth = 0.02;
  19595. /**
  19596. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19597. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19598. */
  19599. _this.renderOverlay = false;
  19600. /** Defines color to use when rendering overlay */
  19601. _this.overlayColor = BABYLON.Color3.Red();
  19602. /** Defines alpha to use when rendering overlay */
  19603. _this.overlayAlpha = 0.5;
  19604. _this._hasVertexAlpha = false;
  19605. _this._useVertexColors = true;
  19606. _this._computeBonesUsingShaders = true;
  19607. _this._numBoneInfluencers = 4;
  19608. _this._applyFog = true;
  19609. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19610. _this.useOctreeForRenderingSelection = true;
  19611. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19612. _this.useOctreeForPicking = true;
  19613. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19614. _this.useOctreeForCollisions = true;
  19615. _this._layerMask = 0x0FFFFFFF;
  19616. /**
  19617. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19618. */
  19619. _this.alwaysSelectAsActiveMesh = false;
  19620. /**
  19621. * Gets or sets the current action manager
  19622. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19623. */
  19624. _this.actionManager = null;
  19625. /**
  19626. * Gets or sets impostor used for physic simulation
  19627. * @see http://doc.babylonjs.com/features/physics_engine
  19628. */
  19629. _this.physicsImpostor = null;
  19630. // Collisions
  19631. _this._checkCollisions = false;
  19632. _this._collisionMask = -1;
  19633. _this._collisionGroup = -1;
  19634. /**
  19635. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19636. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19637. */
  19638. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19639. /**
  19640. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19641. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19642. */
  19643. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19644. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19645. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19646. // Edges
  19647. /**
  19648. * Defines edge width used when edgesRenderer is enabled
  19649. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19650. */
  19651. _this.edgesWidth = 1;
  19652. /**
  19653. * Defines edge color used when edgesRenderer is enabled
  19654. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19655. */
  19656. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19657. // Cache
  19658. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19659. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19660. /** @hidden */
  19661. _this._renderId = 0;
  19662. /** @hidden */
  19663. _this._intersectionsInProgress = new Array();
  19664. /** @hidden */
  19665. _this._unIndexed = false;
  19666. /** @hidden */
  19667. _this._lightSources = new Array();
  19668. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19669. if (collidedMesh === void 0) { collidedMesh = null; }
  19670. //TODO move this to the collision coordinator!
  19671. if (_this.getScene().workerCollisions)
  19672. newPosition.multiplyInPlace(_this._collider._radius);
  19673. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19674. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19675. _this.position.addInPlace(_this._diffPositionForCollisions);
  19676. }
  19677. if (collidedMesh) {
  19678. _this.onCollideObservable.notifyObservers(collidedMesh);
  19679. }
  19680. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19681. };
  19682. _this.getScene().addMesh(_this);
  19683. _this._resyncLightSources();
  19684. return _this;
  19685. }
  19686. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19687. /**
  19688. * No billboard
  19689. */
  19690. get: function () {
  19691. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19692. },
  19693. enumerable: true,
  19694. configurable: true
  19695. });
  19696. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19697. /** Billboard on X axis */
  19698. get: function () {
  19699. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19700. },
  19701. enumerable: true,
  19702. configurable: true
  19703. });
  19704. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19705. /** Billboard on Y axis */
  19706. get: function () {
  19707. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19708. },
  19709. enumerable: true,
  19710. configurable: true
  19711. });
  19712. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19713. /** Billboard on Z axis */
  19714. get: function () {
  19715. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19716. },
  19717. enumerable: true,
  19718. configurable: true
  19719. });
  19720. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19721. /** Billboard on all axes */
  19722. get: function () {
  19723. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19724. },
  19725. enumerable: true,
  19726. configurable: true
  19727. });
  19728. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19729. /**
  19730. * Gets the number of facets in the mesh
  19731. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19732. */
  19733. get: function () {
  19734. return this._facetNb;
  19735. },
  19736. enumerable: true,
  19737. configurable: true
  19738. });
  19739. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19740. /**
  19741. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19742. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19743. */
  19744. get: function () {
  19745. return this._partitioningSubdivisions;
  19746. },
  19747. set: function (nb) {
  19748. this._partitioningSubdivisions = nb;
  19749. },
  19750. enumerable: true,
  19751. configurable: true
  19752. });
  19753. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19754. /**
  19755. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19756. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19757. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19758. */
  19759. get: function () {
  19760. return this._partitioningBBoxRatio;
  19761. },
  19762. set: function (ratio) {
  19763. this._partitioningBBoxRatio = ratio;
  19764. },
  19765. enumerable: true,
  19766. configurable: true
  19767. });
  19768. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19769. /**
  19770. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19771. * Works only for updatable meshes.
  19772. * Doesn't work with multi-materials
  19773. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19774. */
  19775. get: function () {
  19776. return this._facetDepthSort;
  19777. },
  19778. set: function (sort) {
  19779. this._facetDepthSort = sort;
  19780. },
  19781. enumerable: true,
  19782. configurable: true
  19783. });
  19784. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19785. /**
  19786. * The location (Vector3) where the facet depth sort must be computed from.
  19787. * By default, the active camera position.
  19788. * Used only when facet depth sort is enabled
  19789. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19790. */
  19791. get: function () {
  19792. return this._facetDepthSortFrom;
  19793. },
  19794. set: function (location) {
  19795. this._facetDepthSortFrom = location;
  19796. },
  19797. enumerable: true,
  19798. configurable: true
  19799. });
  19800. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19801. /**
  19802. * gets a boolean indicating if facetData is enabled
  19803. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19804. */
  19805. get: function () {
  19806. return this._facetDataEnabled;
  19807. },
  19808. enumerable: true,
  19809. configurable: true
  19810. });
  19811. /** @hidden */
  19812. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19813. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19814. return false;
  19815. }
  19816. this._markSubMeshesAsMiscDirty();
  19817. return true;
  19818. };
  19819. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19820. /** Set a function to call when this mesh collides with another one */
  19821. set: function (callback) {
  19822. if (this._onCollideObserver) {
  19823. this.onCollideObservable.remove(this._onCollideObserver);
  19824. }
  19825. this._onCollideObserver = this.onCollideObservable.add(callback);
  19826. },
  19827. enumerable: true,
  19828. configurable: true
  19829. });
  19830. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19831. /** Set a function to call when the collision's position changes */
  19832. set: function (callback) {
  19833. if (this._onCollisionPositionChangeObserver) {
  19834. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19835. }
  19836. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19837. },
  19838. enumerable: true,
  19839. configurable: true
  19840. });
  19841. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19842. /**
  19843. * 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
  19844. * @see http://doc.babylonjs.com/features/occlusionquery
  19845. */
  19846. get: function () {
  19847. return this._isOccluded;
  19848. },
  19849. set: function (value) {
  19850. this._isOccluded = value;
  19851. },
  19852. enumerable: true,
  19853. configurable: true
  19854. });
  19855. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19856. /**
  19857. * Flag to check the progress status of the query
  19858. * @see http://doc.babylonjs.com/features/occlusionquery
  19859. */
  19860. get: function () {
  19861. return this._isOcclusionQueryInProgress;
  19862. },
  19863. enumerable: true,
  19864. configurable: true
  19865. });
  19866. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19867. /**
  19868. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19869. */
  19870. get: function () {
  19871. return this._visibility;
  19872. },
  19873. /**
  19874. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19875. */
  19876. set: function (value) {
  19877. if (this._visibility === value) {
  19878. return;
  19879. }
  19880. this._visibility = value;
  19881. this._markSubMeshesAsMiscDirty();
  19882. },
  19883. enumerable: true,
  19884. configurable: true
  19885. });
  19886. Object.defineProperty(AbstractMesh.prototype, "material", {
  19887. /** Gets or sets current material */
  19888. get: function () {
  19889. return this._material;
  19890. },
  19891. set: function (value) {
  19892. if (this._material === value) {
  19893. return;
  19894. }
  19895. this._material = value;
  19896. if (this.onMaterialChangedObservable.hasObservers) {
  19897. this.onMaterialChangedObservable.notifyObservers(this);
  19898. }
  19899. if (!this.subMeshes) {
  19900. return;
  19901. }
  19902. this._unBindEffect();
  19903. },
  19904. enumerable: true,
  19905. configurable: true
  19906. });
  19907. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19908. /**
  19909. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19910. * @see http://doc.babylonjs.com/babylon101/shadows
  19911. */
  19912. get: function () {
  19913. return this._receiveShadows;
  19914. },
  19915. set: function (value) {
  19916. if (this._receiveShadows === value) {
  19917. return;
  19918. }
  19919. this._receiveShadows = value;
  19920. this._markSubMeshesAsLightDirty();
  19921. },
  19922. enumerable: true,
  19923. configurable: true
  19924. });
  19925. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19926. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19927. get: function () {
  19928. return this._hasVertexAlpha;
  19929. },
  19930. set: function (value) {
  19931. if (this._hasVertexAlpha === value) {
  19932. return;
  19933. }
  19934. this._hasVertexAlpha = value;
  19935. this._markSubMeshesAsAttributesDirty();
  19936. this._markSubMeshesAsMiscDirty();
  19937. },
  19938. enumerable: true,
  19939. configurable: true
  19940. });
  19941. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19942. /** 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) */
  19943. get: function () {
  19944. return this._useVertexColors;
  19945. },
  19946. set: function (value) {
  19947. if (this._useVertexColors === value) {
  19948. return;
  19949. }
  19950. this._useVertexColors = value;
  19951. this._markSubMeshesAsAttributesDirty();
  19952. },
  19953. enumerable: true,
  19954. configurable: true
  19955. });
  19956. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19957. /**
  19958. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19959. */
  19960. get: function () {
  19961. return this._computeBonesUsingShaders;
  19962. },
  19963. set: function (value) {
  19964. if (this._computeBonesUsingShaders === value) {
  19965. return;
  19966. }
  19967. this._computeBonesUsingShaders = value;
  19968. this._markSubMeshesAsAttributesDirty();
  19969. },
  19970. enumerable: true,
  19971. configurable: true
  19972. });
  19973. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19974. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19975. get: function () {
  19976. return this._numBoneInfluencers;
  19977. },
  19978. set: function (value) {
  19979. if (this._numBoneInfluencers === value) {
  19980. return;
  19981. }
  19982. this._numBoneInfluencers = value;
  19983. this._markSubMeshesAsAttributesDirty();
  19984. },
  19985. enumerable: true,
  19986. configurable: true
  19987. });
  19988. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19989. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19990. get: function () {
  19991. return this._applyFog;
  19992. },
  19993. set: function (value) {
  19994. if (this._applyFog === value) {
  19995. return;
  19996. }
  19997. this._applyFog = value;
  19998. this._markSubMeshesAsMiscDirty();
  19999. },
  20000. enumerable: true,
  20001. configurable: true
  20002. });
  20003. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20004. /**
  20005. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20006. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20007. */
  20008. get: function () {
  20009. return this._layerMask;
  20010. },
  20011. set: function (value) {
  20012. if (value === this._layerMask) {
  20013. return;
  20014. }
  20015. this._layerMask = value;
  20016. this._resyncLightSources();
  20017. },
  20018. enumerable: true,
  20019. configurable: true
  20020. });
  20021. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20022. /**
  20023. * Gets or sets a collision mask used to mask collisions (default is -1).
  20024. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20025. */
  20026. get: function () {
  20027. return this._collisionMask;
  20028. },
  20029. set: function (mask) {
  20030. this._collisionMask = !isNaN(mask) ? mask : -1;
  20031. },
  20032. enumerable: true,
  20033. configurable: true
  20034. });
  20035. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20036. /**
  20037. * Gets or sets the current collision group mask (-1 by default).
  20038. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20039. */
  20040. get: function () {
  20041. return this._collisionGroup;
  20042. },
  20043. set: function (mask) {
  20044. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20045. },
  20046. enumerable: true,
  20047. configurable: true
  20048. });
  20049. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20050. /** @hidden */
  20051. get: function () {
  20052. return null;
  20053. },
  20054. enumerable: true,
  20055. configurable: true
  20056. });
  20057. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20058. get: function () {
  20059. return this._skeleton;
  20060. },
  20061. /**
  20062. * Gets or sets a skeleton to apply skining transformations
  20063. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20064. */
  20065. set: function (value) {
  20066. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20067. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20068. }
  20069. if (value && value.needInitialSkinMatrix) {
  20070. value._registerMeshWithPoseMatrix(this);
  20071. }
  20072. this._skeleton = value;
  20073. if (!this._skeleton) {
  20074. this._bonesTransformMatrices = null;
  20075. }
  20076. this._markSubMeshesAsAttributesDirty();
  20077. },
  20078. enumerable: true,
  20079. configurable: true
  20080. });
  20081. /**
  20082. * Returns the string "AbstractMesh"
  20083. * @returns "AbstractMesh"
  20084. */
  20085. AbstractMesh.prototype.getClassName = function () {
  20086. return "AbstractMesh";
  20087. };
  20088. /**
  20089. * Gets a string representation of the current mesh
  20090. * @param fullDetails defines a boolean indicating if full details must be included
  20091. * @returns a string representation of the current mesh
  20092. */
  20093. AbstractMesh.prototype.toString = function (fullDetails) {
  20094. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20095. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20096. if (this._skeleton) {
  20097. ret += ", skeleton: " + this._skeleton.name;
  20098. }
  20099. if (fullDetails) {
  20100. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20101. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20102. }
  20103. return ret;
  20104. };
  20105. /** @hidden */
  20106. AbstractMesh.prototype._rebuild = function () {
  20107. if (this._occlusionQuery) {
  20108. this._occlusionQuery = null;
  20109. }
  20110. if (this._edgesRenderer) {
  20111. this._edgesRenderer._rebuild();
  20112. }
  20113. if (!this.subMeshes) {
  20114. return;
  20115. }
  20116. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20117. var subMesh = _a[_i];
  20118. subMesh._rebuild();
  20119. }
  20120. };
  20121. /** @hidden */
  20122. AbstractMesh.prototype._resyncLightSources = function () {
  20123. this._lightSources.length = 0;
  20124. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20125. var light = _a[_i];
  20126. if (!light.isEnabled()) {
  20127. continue;
  20128. }
  20129. if (light.canAffectMesh(this)) {
  20130. this._lightSources.push(light);
  20131. }
  20132. }
  20133. this._markSubMeshesAsLightDirty();
  20134. };
  20135. /** @hidden */
  20136. AbstractMesh.prototype._resyncLighSource = function (light) {
  20137. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20138. var index = this._lightSources.indexOf(light);
  20139. if (index === -1) {
  20140. if (!isIn) {
  20141. return;
  20142. }
  20143. this._lightSources.push(light);
  20144. }
  20145. else {
  20146. if (isIn) {
  20147. return;
  20148. }
  20149. this._lightSources.splice(index, 1);
  20150. }
  20151. this._markSubMeshesAsLightDirty();
  20152. };
  20153. /** @hidden */
  20154. AbstractMesh.prototype._unBindEffect = function () {
  20155. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20156. var subMesh = _a[_i];
  20157. subMesh.setEffect(null);
  20158. }
  20159. };
  20160. /** @hidden */
  20161. AbstractMesh.prototype._removeLightSource = function (light) {
  20162. var index = this._lightSources.indexOf(light);
  20163. if (index === -1) {
  20164. return;
  20165. }
  20166. this._lightSources.splice(index, 1);
  20167. this._markSubMeshesAsLightDirty();
  20168. };
  20169. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20170. if (!this.subMeshes) {
  20171. return;
  20172. }
  20173. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20174. var subMesh = _a[_i];
  20175. if (subMesh._materialDefines) {
  20176. func(subMesh._materialDefines);
  20177. }
  20178. }
  20179. };
  20180. /** @hidden */
  20181. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20182. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20183. };
  20184. /** @hidden */
  20185. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20186. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20187. };
  20188. /** @hidden */
  20189. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20190. if (!this.subMeshes) {
  20191. return;
  20192. }
  20193. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20194. var subMesh = _a[_i];
  20195. var material = subMesh.getMaterial();
  20196. if (material) {
  20197. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20198. }
  20199. }
  20200. };
  20201. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20202. /**
  20203. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20204. */
  20205. get: function () {
  20206. return this._scaling;
  20207. },
  20208. set: function (newScaling) {
  20209. this._scaling = newScaling;
  20210. if (this.physicsImpostor) {
  20211. this.physicsImpostor.forceUpdate();
  20212. }
  20213. },
  20214. enumerable: true,
  20215. configurable: true
  20216. });
  20217. // Methods
  20218. /**
  20219. * Disables the mesh edge rendering mode
  20220. * @returns the currentAbstractMesh
  20221. */
  20222. AbstractMesh.prototype.disableEdgesRendering = function () {
  20223. if (this._edgesRenderer) {
  20224. this._edgesRenderer.dispose();
  20225. this._edgesRenderer = null;
  20226. }
  20227. return this;
  20228. };
  20229. /**
  20230. * Enables the edge rendering mode on the mesh.
  20231. * This mode makes the mesh edges visible
  20232. * @param epsilon defines the maximal distance between two angles to detect a face
  20233. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20234. * @returns the currentAbstractMesh
  20235. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20236. */
  20237. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20238. if (epsilon === void 0) { epsilon = 0.95; }
  20239. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20240. this.disableEdgesRendering();
  20241. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20242. return this;
  20243. };
  20244. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20245. /**
  20246. * Gets the edgesRenderer associated with the mesh
  20247. */
  20248. get: function () {
  20249. return this._edgesRenderer;
  20250. },
  20251. enumerable: true,
  20252. configurable: true
  20253. });
  20254. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20255. /**
  20256. * Returns true if the mesh is blocked. Implemented by child classes
  20257. */
  20258. get: function () {
  20259. return false;
  20260. },
  20261. enumerable: true,
  20262. configurable: true
  20263. });
  20264. /**
  20265. * Returns the mesh itself by default. Implemented by child classes
  20266. * @param camera defines the camera to use to pick the right LOD level
  20267. * @returns the currentAbstractMesh
  20268. */
  20269. AbstractMesh.prototype.getLOD = function (camera) {
  20270. return this;
  20271. };
  20272. /**
  20273. * Returns 0 by default. Implemented by child classes
  20274. * @returns an integer
  20275. */
  20276. AbstractMesh.prototype.getTotalVertices = function () {
  20277. return 0;
  20278. };
  20279. /**
  20280. * Returns null by default. Implemented by child classes
  20281. * @returns null
  20282. */
  20283. AbstractMesh.prototype.getIndices = function () {
  20284. return null;
  20285. };
  20286. /**
  20287. * Returns the array of the requested vertex data kind. Implemented by child classes
  20288. * @param kind defines the vertex data kind to use
  20289. * @returns null
  20290. */
  20291. AbstractMesh.prototype.getVerticesData = function (kind) {
  20292. return null;
  20293. };
  20294. /**
  20295. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20296. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20297. * Note that a new underlying VertexBuffer object is created each call.
  20298. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20299. * @param kind defines vertex data kind:
  20300. * * BABYLON.VertexBuffer.PositionKind
  20301. * * BABYLON.VertexBuffer.UVKind
  20302. * * BABYLON.VertexBuffer.UV2Kind
  20303. * * BABYLON.VertexBuffer.UV3Kind
  20304. * * BABYLON.VertexBuffer.UV4Kind
  20305. * * BABYLON.VertexBuffer.UV5Kind
  20306. * * BABYLON.VertexBuffer.UV6Kind
  20307. * * BABYLON.VertexBuffer.ColorKind
  20308. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20309. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20310. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20311. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20312. * @param data defines the data source
  20313. * @param updatable defines if the data must be flagged as updatable (or static)
  20314. * @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
  20315. * @returns the current mesh
  20316. */
  20317. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20318. return this;
  20319. };
  20320. /**
  20321. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20322. * If the mesh has no geometry, it is simply returned as it is.
  20323. * @param kind defines vertex data kind:
  20324. * * BABYLON.VertexBuffer.PositionKind
  20325. * * BABYLON.VertexBuffer.UVKind
  20326. * * BABYLON.VertexBuffer.UV2Kind
  20327. * * BABYLON.VertexBuffer.UV3Kind
  20328. * * BABYLON.VertexBuffer.UV4Kind
  20329. * * BABYLON.VertexBuffer.UV5Kind
  20330. * * BABYLON.VertexBuffer.UV6Kind
  20331. * * BABYLON.VertexBuffer.ColorKind
  20332. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20333. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20334. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20335. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20336. * @param data defines the data source
  20337. * @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
  20338. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20339. * @returns the current mesh
  20340. */
  20341. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20342. return this;
  20343. };
  20344. /**
  20345. * Sets the mesh indices,
  20346. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20347. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20348. * @param totalVertices Defines the total number of vertices
  20349. * @returns the current mesh
  20350. */
  20351. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20352. return this;
  20353. };
  20354. /**
  20355. * Gets a boolean indicating if specific vertex data is present
  20356. * @param kind defines the vertex data kind to use
  20357. * @returns true is data kind is present
  20358. */
  20359. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20360. return false;
  20361. };
  20362. /**
  20363. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20364. * @returns a BoundingInfo
  20365. */
  20366. AbstractMesh.prototype.getBoundingInfo = function () {
  20367. if (this._masterMesh) {
  20368. return this._masterMesh.getBoundingInfo();
  20369. }
  20370. if (!this._boundingInfo) {
  20371. // this._boundingInfo is being created here
  20372. this._updateBoundingInfo();
  20373. }
  20374. // cannot be null.
  20375. return this._boundingInfo;
  20376. };
  20377. /**
  20378. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20379. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20380. * @returns the current mesh
  20381. */
  20382. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20383. if (includeDescendants === void 0) { includeDescendants = true; }
  20384. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20385. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20386. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20387. if (maxDimension === 0) {
  20388. return this;
  20389. }
  20390. var scale = 1 / maxDimension;
  20391. this.scaling.scaleInPlace(scale);
  20392. return this;
  20393. };
  20394. /**
  20395. * Overwrite the current bounding info
  20396. * @param boundingInfo defines the new bounding info
  20397. * @returns the current mesh
  20398. */
  20399. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20400. this._boundingInfo = boundingInfo;
  20401. return this;
  20402. };
  20403. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20404. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20405. get: function () {
  20406. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20407. },
  20408. enumerable: true,
  20409. configurable: true
  20410. });
  20411. /** @hidden */
  20412. AbstractMesh.prototype._preActivate = function () {
  20413. };
  20414. /** @hidden */
  20415. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20416. };
  20417. /** @hidden */
  20418. AbstractMesh.prototype._activate = function (renderId) {
  20419. this._renderId = renderId;
  20420. };
  20421. /**
  20422. * Gets the current world matrix
  20423. * @returns a Matrix
  20424. */
  20425. AbstractMesh.prototype.getWorldMatrix = function () {
  20426. if (this._masterMesh) {
  20427. return this._masterMesh.getWorldMatrix();
  20428. }
  20429. return _super.prototype.getWorldMatrix.call(this);
  20430. };
  20431. /** @hidden */
  20432. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20433. if (this._masterMesh) {
  20434. return this._masterMesh._getWorldMatrixDeterminant();
  20435. }
  20436. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20437. };
  20438. // ================================== Point of View Movement =================================
  20439. /**
  20440. * Perform relative position change from the point of view of behind the front of the mesh.
  20441. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20442. * Supports definition of mesh facing forward or backward
  20443. * @param amountRight defines the distance on the right axis
  20444. * @param amountUp defines the distance on the up axis
  20445. * @param amountForward defines the distance on the forward axis
  20446. * @returns the current mesh
  20447. */
  20448. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20449. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20450. return this;
  20451. };
  20452. /**
  20453. * Calculate relative position change from the point of view of behind the front of the mesh.
  20454. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20455. * Supports definition of mesh facing forward or backward
  20456. * @param amountRight defines the distance on the right axis
  20457. * @param amountUp defines the distance on the up axis
  20458. * @param amountForward defines the distance on the forward axis
  20459. * @returns the new displacement vector
  20460. */
  20461. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20462. var rotMatrix = new BABYLON.Matrix();
  20463. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20464. rotQuaternion.toRotationMatrix(rotMatrix);
  20465. var translationDelta = BABYLON.Vector3.Zero();
  20466. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20467. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20468. return translationDelta;
  20469. };
  20470. // ================================== Point of View Rotation =================================
  20471. /**
  20472. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20473. * Supports definition of mesh facing forward or backward
  20474. * @param flipBack defines the flip
  20475. * @param twirlClockwise defines the twirl
  20476. * @param tiltRight defines the tilt
  20477. * @returns the current mesh
  20478. */
  20479. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20480. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20481. return this;
  20482. };
  20483. /**
  20484. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20485. * Supports definition of mesh facing forward or backward.
  20486. * @param flipBack defines the flip
  20487. * @param twirlClockwise defines the twirl
  20488. * @param tiltRight defines the tilt
  20489. * @returns the new rotation vector
  20490. */
  20491. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20492. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20493. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20494. };
  20495. /**
  20496. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20497. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20498. * @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
  20499. * @returns the new bounding vectors
  20500. */
  20501. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20502. if (includeDescendants === void 0) { includeDescendants = true; }
  20503. if (predicate === void 0) { predicate = null; }
  20504. // Ensures that all world matrix will be recomputed.
  20505. this.getScene().incrementRenderId();
  20506. this.computeWorldMatrix(true);
  20507. var min;
  20508. var max;
  20509. var boundingInfo = this.getBoundingInfo();
  20510. if (!this.subMeshes) {
  20511. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20512. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20513. }
  20514. else {
  20515. min = boundingInfo.boundingBox.minimumWorld;
  20516. max = boundingInfo.boundingBox.maximumWorld;
  20517. }
  20518. if (includeDescendants) {
  20519. var descendants = this.getDescendants(false);
  20520. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20521. var descendant = descendants_1[_i];
  20522. var childMesh = descendant;
  20523. childMesh.computeWorldMatrix(true);
  20524. // Filters meshes based on custom predicate function.
  20525. if (predicate && !predicate(childMesh)) {
  20526. continue;
  20527. }
  20528. //make sure we have the needed params to get mix and max
  20529. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20530. continue;
  20531. }
  20532. var childBoundingInfo = childMesh.getBoundingInfo();
  20533. var boundingBox = childBoundingInfo.boundingBox;
  20534. var minBox = boundingBox.minimumWorld;
  20535. var maxBox = boundingBox.maximumWorld;
  20536. BABYLON.Tools.CheckExtends(minBox, min, max);
  20537. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20538. }
  20539. }
  20540. return {
  20541. min: min,
  20542. max: max
  20543. };
  20544. };
  20545. /** @hidden */
  20546. AbstractMesh.prototype._updateBoundingInfo = function () {
  20547. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20548. this._boundingInfo.update(this.worldMatrixFromCache);
  20549. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20550. return this;
  20551. };
  20552. /** @hidden */
  20553. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20554. if (!this.subMeshes) {
  20555. return this;
  20556. }
  20557. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20558. var subMesh = this.subMeshes[subIndex];
  20559. if (!subMesh.IsGlobal) {
  20560. subMesh.updateBoundingInfo(matrix);
  20561. }
  20562. }
  20563. return this;
  20564. };
  20565. /** @hidden */
  20566. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20567. // Bounding info
  20568. this._updateBoundingInfo();
  20569. };
  20570. /**
  20571. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20572. * A mesh is in the frustum if its bounding box intersects the frustum
  20573. * @param frustumPlanes defines the frustum to test
  20574. * @returns true if the mesh is in the frustum planes
  20575. */
  20576. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20577. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20578. };
  20579. /**
  20580. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20581. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20582. * @param frustumPlanes defines the frustum to test
  20583. * @returns true if the mesh is completely in the frustum planes
  20584. */
  20585. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20586. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20587. };
  20588. /**
  20589. * True if the mesh intersects another mesh or a SolidParticle object
  20590. * @param mesh defines a target mesh or SolidParticle to test
  20591. * @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)
  20592. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20593. * @returns true if there is an intersection
  20594. */
  20595. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20596. if (precise === void 0) { precise = false; }
  20597. if (!this._boundingInfo || !mesh._boundingInfo) {
  20598. return false;
  20599. }
  20600. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20601. return true;
  20602. }
  20603. if (includeDescendants) {
  20604. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20605. var child = _a[_i];
  20606. if (child.intersectsMesh(mesh, precise, true)) {
  20607. return true;
  20608. }
  20609. }
  20610. }
  20611. return false;
  20612. };
  20613. /**
  20614. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20615. * @param point defines the point to test
  20616. * @returns true if there is an intersection
  20617. */
  20618. AbstractMesh.prototype.intersectsPoint = function (point) {
  20619. if (!this._boundingInfo) {
  20620. return false;
  20621. }
  20622. return this._boundingInfo.intersectsPoint(point);
  20623. };
  20624. /**
  20625. * Gets the current physics impostor
  20626. * @see http://doc.babylonjs.com/features/physics_engine
  20627. * @returns a physics impostor or null
  20628. */
  20629. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20630. return this.physicsImpostor;
  20631. };
  20632. /**
  20633. * Gets the position of the current mesh in camera space
  20634. * @param camera defines the camera to use
  20635. * @returns a position
  20636. */
  20637. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20638. if (camera === void 0) { camera = null; }
  20639. if (!camera) {
  20640. camera = this.getScene().activeCamera;
  20641. }
  20642. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20643. };
  20644. /**
  20645. * Returns the distance from the mesh to the active camera
  20646. * @param camera defines the camera to use
  20647. * @returns the distance
  20648. */
  20649. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20650. if (camera === void 0) { camera = null; }
  20651. if (!camera) {
  20652. camera = this.getScene().activeCamera;
  20653. }
  20654. return this.absolutePosition.subtract(camera.position).length();
  20655. };
  20656. /**
  20657. * Apply a physic impulse to the mesh
  20658. * @param force defines the force to apply
  20659. * @param contactPoint defines where to apply the force
  20660. * @returns the current mesh
  20661. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20662. */
  20663. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20664. if (!this.physicsImpostor) {
  20665. return this;
  20666. }
  20667. this.physicsImpostor.applyImpulse(force, contactPoint);
  20668. return this;
  20669. };
  20670. /**
  20671. * Creates a physic joint between two meshes
  20672. * @param otherMesh defines the other mesh to use
  20673. * @param pivot1 defines the pivot to use on this mesh
  20674. * @param pivot2 defines the pivot to use on the other mesh
  20675. * @param options defines additional options (can be plugin dependent)
  20676. * @returns the current mesh
  20677. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20678. */
  20679. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20680. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20681. return this;
  20682. }
  20683. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20684. mainPivot: pivot1,
  20685. connectedPivot: pivot2,
  20686. nativeParams: options
  20687. });
  20688. return this;
  20689. };
  20690. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20691. // Collisions
  20692. /**
  20693. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20694. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20695. */
  20696. get: function () {
  20697. return this._checkCollisions;
  20698. },
  20699. set: function (collisionEnabled) {
  20700. this._checkCollisions = collisionEnabled;
  20701. if (this.getScene().workerCollisions) {
  20702. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20703. }
  20704. },
  20705. enumerable: true,
  20706. configurable: true
  20707. });
  20708. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20709. /**
  20710. * Gets Collider object used to compute collisions (not physics)
  20711. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20712. */
  20713. get: function () {
  20714. return this._collider;
  20715. },
  20716. enumerable: true,
  20717. configurable: true
  20718. });
  20719. /**
  20720. * Move the mesh using collision engine
  20721. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20722. * @param displacement defines the requested displacement vector
  20723. * @returns the current mesh
  20724. */
  20725. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20726. var globalPosition = this.getAbsolutePosition();
  20727. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20728. if (!this._collider) {
  20729. this._collider = new BABYLON.Collider();
  20730. }
  20731. this._collider._radius = this.ellipsoid;
  20732. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20733. return this;
  20734. };
  20735. // Submeshes octree
  20736. /**
  20737. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20738. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20739. * @param maxCapacity defines the maximum size of each block (64 by default)
  20740. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20741. * @returns the new octree
  20742. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20743. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20744. */
  20745. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20746. if (maxCapacity === void 0) { maxCapacity = 64; }
  20747. if (maxDepth === void 0) { maxDepth = 2; }
  20748. if (!this._submeshesOctree) {
  20749. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20750. }
  20751. this.computeWorldMatrix(true);
  20752. var boundingInfo = this.getBoundingInfo();
  20753. // Update octree
  20754. var bbox = boundingInfo.boundingBox;
  20755. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20756. return this._submeshesOctree;
  20757. };
  20758. // Collisions
  20759. /** @hidden */
  20760. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20761. this._generatePointsArray();
  20762. if (!this._positions) {
  20763. return this;
  20764. }
  20765. // Transformation
  20766. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20767. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20768. subMesh._lastColliderWorldVertices = [];
  20769. subMesh._trianglePlanes = [];
  20770. var start = subMesh.verticesStart;
  20771. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20772. for (var i = start; i < end; i++) {
  20773. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20774. }
  20775. }
  20776. // Collide
  20777. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20778. if (collider.collisionFound) {
  20779. collider.collidedMesh = this;
  20780. }
  20781. return this;
  20782. };
  20783. /** @hidden */
  20784. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20785. var subMeshes;
  20786. var len;
  20787. // Octrees
  20788. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20789. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20790. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20791. len = intersections.length;
  20792. subMeshes = intersections.data;
  20793. }
  20794. else {
  20795. subMeshes = this.subMeshes;
  20796. len = subMeshes.length;
  20797. }
  20798. for (var index = 0; index < len; index++) {
  20799. var subMesh = subMeshes[index];
  20800. // Bounding test
  20801. if (len > 1 && !subMesh._checkCollision(collider))
  20802. continue;
  20803. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20804. }
  20805. return this;
  20806. };
  20807. /** @hidden */
  20808. AbstractMesh.prototype._checkCollision = function (collider) {
  20809. // Bounding box test
  20810. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20811. return this;
  20812. // Transformation matrix
  20813. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20814. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20815. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20816. return this;
  20817. };
  20818. // Picking
  20819. /** @hidden */
  20820. AbstractMesh.prototype._generatePointsArray = function () {
  20821. return false;
  20822. };
  20823. /**
  20824. * Checks if the passed Ray intersects with the mesh
  20825. * @param ray defines the ray to use
  20826. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20827. * @returns the picking info
  20828. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20829. */
  20830. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20831. var pickingInfo = new BABYLON.PickingInfo();
  20832. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20833. return pickingInfo;
  20834. }
  20835. if (!this._generatePointsArray()) {
  20836. return pickingInfo;
  20837. }
  20838. var intersectInfo = null;
  20839. // Octrees
  20840. var subMeshes;
  20841. var len;
  20842. if (this._submeshesOctree && this.useOctreeForPicking) {
  20843. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20844. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20845. len = intersections.length;
  20846. subMeshes = intersections.data;
  20847. }
  20848. else {
  20849. subMeshes = this.subMeshes;
  20850. len = subMeshes.length;
  20851. }
  20852. for (var index = 0; index < len; index++) {
  20853. var subMesh = subMeshes[index];
  20854. // Bounding test
  20855. if (len > 1 && !subMesh.canIntersects(ray))
  20856. continue;
  20857. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20858. if (currentIntersectInfo) {
  20859. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20860. intersectInfo = currentIntersectInfo;
  20861. intersectInfo.subMeshId = index;
  20862. if (fastCheck) {
  20863. break;
  20864. }
  20865. }
  20866. }
  20867. }
  20868. if (intersectInfo) {
  20869. // Get picked point
  20870. var world = this.getWorldMatrix();
  20871. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20872. var direction = ray.direction.clone();
  20873. direction = direction.scale(intersectInfo.distance);
  20874. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20875. var pickedPoint = worldOrigin.add(worldDirection);
  20876. // Return result
  20877. pickingInfo.hit = true;
  20878. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20879. pickingInfo.pickedPoint = pickedPoint;
  20880. pickingInfo.pickedMesh = this;
  20881. pickingInfo.bu = intersectInfo.bu || 0;
  20882. pickingInfo.bv = intersectInfo.bv || 0;
  20883. pickingInfo.faceId = intersectInfo.faceId;
  20884. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20885. return pickingInfo;
  20886. }
  20887. return pickingInfo;
  20888. };
  20889. /**
  20890. * Clones the current mesh
  20891. * @param name defines the mesh name
  20892. * @param newParent defines the new mesh parent
  20893. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20894. * @returns the new mesh
  20895. */
  20896. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20897. return null;
  20898. };
  20899. /**
  20900. * Disposes all the submeshes of the current meshnp
  20901. * @returns the current mesh
  20902. */
  20903. AbstractMesh.prototype.releaseSubMeshes = function () {
  20904. if (this.subMeshes) {
  20905. while (this.subMeshes.length) {
  20906. this.subMeshes[0].dispose();
  20907. }
  20908. }
  20909. else {
  20910. this.subMeshes = new Array();
  20911. }
  20912. return this;
  20913. };
  20914. /**
  20915. * Releases resources associated with this abstract mesh.
  20916. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20917. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20918. */
  20919. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20920. var _this = this;
  20921. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20922. var index;
  20923. // Smart Array Retainers.
  20924. this.getScene().freeActiveMeshes();
  20925. this.getScene().freeRenderingGroups();
  20926. // Action manager
  20927. if (this.actionManager !== undefined && this.actionManager !== null) {
  20928. this.actionManager.dispose();
  20929. this.actionManager = null;
  20930. }
  20931. // Skeleton
  20932. this._skeleton = null;
  20933. // Physics
  20934. if (this.physicsImpostor) {
  20935. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20936. }
  20937. // Intersections in progress
  20938. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20939. var other = this._intersectionsInProgress[index];
  20940. var pos = other._intersectionsInProgress.indexOf(this);
  20941. other._intersectionsInProgress.splice(pos, 1);
  20942. }
  20943. this._intersectionsInProgress = [];
  20944. // Lights
  20945. var lights = this.getScene().lights;
  20946. lights.forEach(function (light) {
  20947. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20948. if (meshIndex !== -1) {
  20949. light.includedOnlyMeshes.splice(meshIndex, 1);
  20950. }
  20951. meshIndex = light.excludedMeshes.indexOf(_this);
  20952. if (meshIndex !== -1) {
  20953. light.excludedMeshes.splice(meshIndex, 1);
  20954. }
  20955. // Shadow generators
  20956. var generator = light.getShadowGenerator();
  20957. if (generator) {
  20958. var shadowMap = generator.getShadowMap();
  20959. if (shadowMap && shadowMap.renderList) {
  20960. meshIndex = shadowMap.renderList.indexOf(_this);
  20961. if (meshIndex !== -1) {
  20962. shadowMap.renderList.splice(meshIndex, 1);
  20963. }
  20964. }
  20965. }
  20966. });
  20967. // Edges
  20968. if (this._edgesRenderer) {
  20969. this._edgesRenderer.dispose();
  20970. this._edgesRenderer = null;
  20971. }
  20972. // SubMeshes
  20973. if (this.getClassName() !== "InstancedMesh") {
  20974. this.releaseSubMeshes();
  20975. }
  20976. // Octree
  20977. var sceneOctree = this.getScene().selectionOctree;
  20978. if (sceneOctree !== undefined && sceneOctree !== null) {
  20979. var index = sceneOctree.dynamicContent.indexOf(this);
  20980. if (index !== -1) {
  20981. sceneOctree.dynamicContent.splice(index, 1);
  20982. }
  20983. }
  20984. // Query
  20985. var engine = this.getScene().getEngine();
  20986. if (this._occlusionQuery) {
  20987. this._isOcclusionQueryInProgress = false;
  20988. engine.deleteQuery(this._occlusionQuery);
  20989. this._occlusionQuery = null;
  20990. }
  20991. // Engine
  20992. engine.wipeCaches();
  20993. // Remove from scene
  20994. this.getScene().removeMesh(this);
  20995. if (disposeMaterialAndTextures) {
  20996. if (this.material) {
  20997. this.material.dispose(false, true);
  20998. }
  20999. }
  21000. if (!doNotRecurse) {
  21001. // Particles
  21002. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21003. if (this.getScene().particleSystems[index].emitter === this) {
  21004. this.getScene().particleSystems[index].dispose();
  21005. index--;
  21006. }
  21007. }
  21008. }
  21009. // facet data
  21010. if (this._facetDataEnabled) {
  21011. this.disableFacetData();
  21012. }
  21013. this.onAfterWorldMatrixUpdateObservable.clear();
  21014. this.onCollideObservable.clear();
  21015. this.onCollisionPositionChangeObservable.clear();
  21016. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21017. };
  21018. /**
  21019. * Adds the passed mesh as a child to the current mesh
  21020. * @param mesh defines the child mesh
  21021. * @returns the current mesh
  21022. */
  21023. AbstractMesh.prototype.addChild = function (mesh) {
  21024. mesh.setParent(this);
  21025. return this;
  21026. };
  21027. /**
  21028. * Removes the passed mesh from the current mesh children list
  21029. * @param mesh defines the child mesh
  21030. * @returns the current mesh
  21031. */
  21032. AbstractMesh.prototype.removeChild = function (mesh) {
  21033. mesh.setParent(null);
  21034. return this;
  21035. };
  21036. // Facet data
  21037. /** @hidden */
  21038. AbstractMesh.prototype._initFacetData = function () {
  21039. if (!this._facetNormals) {
  21040. this._facetNormals = new Array();
  21041. }
  21042. if (!this._facetPositions) {
  21043. this._facetPositions = new Array();
  21044. }
  21045. if (!this._facetPartitioning) {
  21046. this._facetPartitioning = new Array();
  21047. }
  21048. this._facetNb = (this.getIndices().length / 3) | 0;
  21049. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21050. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21051. for (var f = 0; f < this._facetNb; f++) {
  21052. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21053. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21054. }
  21055. this._facetDataEnabled = true;
  21056. return this;
  21057. };
  21058. /**
  21059. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21060. * This method can be called within the render loop.
  21061. * 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
  21062. * @returns the current mesh
  21063. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21064. */
  21065. AbstractMesh.prototype.updateFacetData = function () {
  21066. if (!this._facetDataEnabled) {
  21067. this._initFacetData();
  21068. }
  21069. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21070. var indices = this.getIndices();
  21071. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21072. var bInfo = this.getBoundingInfo();
  21073. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21074. // init arrays, matrix and sort function on first call
  21075. this._facetDepthSortEnabled = true;
  21076. if (indices instanceof Uint16Array) {
  21077. this._depthSortedIndices = new Uint16Array(indices);
  21078. }
  21079. else if (indices instanceof Uint32Array) {
  21080. this._depthSortedIndices = new Uint32Array(indices);
  21081. }
  21082. else {
  21083. var needs32bits = false;
  21084. for (var i = 0; i < indices.length; i++) {
  21085. if (indices[i] > 65535) {
  21086. needs32bits = true;
  21087. break;
  21088. }
  21089. }
  21090. if (needs32bits) {
  21091. this._depthSortedIndices = new Uint32Array(indices);
  21092. }
  21093. else {
  21094. this._depthSortedIndices = new Uint16Array(indices);
  21095. }
  21096. }
  21097. this._facetDepthSortFunction = function (f1, f2) {
  21098. return (f2.sqDistance - f1.sqDistance);
  21099. };
  21100. if (!this._facetDepthSortFrom) {
  21101. var camera = this.getScene().activeCamera;
  21102. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21103. }
  21104. this._depthSortedFacets = [];
  21105. for (var f = 0; f < this._facetNb; f++) {
  21106. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21107. this._depthSortedFacets.push(depthSortedFacet);
  21108. }
  21109. this._invertedMatrix = BABYLON.Matrix.Identity();
  21110. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21111. }
  21112. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21113. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21114. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21115. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21116. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21117. this._subDiv.max = this._partitioningSubdivisions;
  21118. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21119. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21120. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21121. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21122. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21123. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21124. // set the parameters for ComputeNormals()
  21125. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21126. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21127. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21128. this._facetParameters.bInfo = bInfo;
  21129. this._facetParameters.bbSize = this._bbSize;
  21130. this._facetParameters.subDiv = this._subDiv;
  21131. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21132. this._facetParameters.depthSort = this._facetDepthSort;
  21133. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21134. this.computeWorldMatrix(true);
  21135. this._worldMatrix.invertToRef(this._invertedMatrix);
  21136. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21137. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21138. }
  21139. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21140. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21141. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21142. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21143. var l = (this._depthSortedIndices.length / 3) | 0;
  21144. for (var f = 0; f < l; f++) {
  21145. var sind = this._depthSortedFacets[f].ind;
  21146. this._depthSortedIndices[f * 3] = indices[sind];
  21147. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21148. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21149. }
  21150. this.updateIndices(this._depthSortedIndices);
  21151. }
  21152. return this;
  21153. };
  21154. /**
  21155. * Returns the facetLocalNormals array.
  21156. * The normals are expressed in the mesh local spac
  21157. * @returns an array of Vector3
  21158. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21159. */
  21160. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21161. if (!this._facetNormals) {
  21162. this.updateFacetData();
  21163. }
  21164. return this._facetNormals;
  21165. };
  21166. /**
  21167. * Returns the facetLocalPositions array.
  21168. * The facet positions are expressed in the mesh local space
  21169. * @returns an array of Vector3
  21170. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21171. */
  21172. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21173. if (!this._facetPositions) {
  21174. this.updateFacetData();
  21175. }
  21176. return this._facetPositions;
  21177. };
  21178. /**
  21179. * Returns the facetLocalPartioning array
  21180. * @returns an array of array of numbers
  21181. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21182. */
  21183. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21184. if (!this._facetPartitioning) {
  21185. this.updateFacetData();
  21186. }
  21187. return this._facetPartitioning;
  21188. };
  21189. /**
  21190. * Returns the i-th facet position in the world system.
  21191. * This method allocates a new Vector3 per call
  21192. * @param i defines the facet index
  21193. * @returns a new Vector3
  21194. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21195. */
  21196. AbstractMesh.prototype.getFacetPosition = function (i) {
  21197. var pos = BABYLON.Vector3.Zero();
  21198. this.getFacetPositionToRef(i, pos);
  21199. return pos;
  21200. };
  21201. /**
  21202. * Sets the reference Vector3 with the i-th facet position in the world system
  21203. * @param i defines the facet index
  21204. * @param ref defines the target vector
  21205. * @returns the current mesh
  21206. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21207. */
  21208. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21209. var localPos = (this.getFacetLocalPositions())[i];
  21210. var world = this.getWorldMatrix();
  21211. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21212. return this;
  21213. };
  21214. /**
  21215. * Returns the i-th facet normal in the world system.
  21216. * This method allocates a new Vector3 per call
  21217. * @param i defines the facet index
  21218. * @returns a new Vector3
  21219. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21220. */
  21221. AbstractMesh.prototype.getFacetNormal = function (i) {
  21222. var norm = BABYLON.Vector3.Zero();
  21223. this.getFacetNormalToRef(i, norm);
  21224. return norm;
  21225. };
  21226. /**
  21227. * Sets the reference Vector3 with the i-th facet normal in the world system
  21228. * @param i defines the facet index
  21229. * @param ref defines the target vector
  21230. * @returns the current mesh
  21231. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21232. */
  21233. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21234. var localNorm = (this.getFacetLocalNormals())[i];
  21235. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21236. return this;
  21237. };
  21238. /**
  21239. * 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)
  21240. * @param x defines x coordinate
  21241. * @param y defines y coordinate
  21242. * @param z defines z coordinate
  21243. * @returns the array of facet indexes
  21244. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21245. */
  21246. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21247. var bInfo = this.getBoundingInfo();
  21248. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21249. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21250. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21251. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21252. return null;
  21253. }
  21254. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21255. };
  21256. /**
  21257. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21258. * @param projected sets as the (x,y,z) world projection on the facet
  21259. * @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
  21260. * @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
  21261. * @param x defines x coordinate
  21262. * @param y defines y coordinate
  21263. * @param z defines z coordinate
  21264. * @returns the face index if found (or null instead)
  21265. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21266. */
  21267. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21268. if (checkFace === void 0) { checkFace = false; }
  21269. if (facing === void 0) { facing = true; }
  21270. var world = this.getWorldMatrix();
  21271. var invMat = BABYLON.Tmp.Matrix[5];
  21272. world.invertToRef(invMat);
  21273. var invVect = BABYLON.Tmp.Vector3[8];
  21274. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21275. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21276. if (projected) {
  21277. // tranform the local computed projected vector to world coordinates
  21278. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21279. }
  21280. return closest;
  21281. };
  21282. /**
  21283. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21284. * @param projected sets as the (x,y,z) local projection on the facet
  21285. * @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
  21286. * @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
  21287. * @param x defines x coordinate
  21288. * @param y defines y coordinate
  21289. * @param z defines z coordinate
  21290. * @returns the face index if found (or null instead)
  21291. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21292. */
  21293. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21294. if (checkFace === void 0) { checkFace = false; }
  21295. if (facing === void 0) { facing = true; }
  21296. var closest = null;
  21297. var tmpx = 0.0;
  21298. var tmpy = 0.0;
  21299. var tmpz = 0.0;
  21300. var d = 0.0; // tmp dot facet normal * facet position
  21301. var t0 = 0.0;
  21302. var projx = 0.0;
  21303. var projy = 0.0;
  21304. var projz = 0.0;
  21305. // Get all the facets in the same partitioning block than (x, y, z)
  21306. var facetPositions = this.getFacetLocalPositions();
  21307. var facetNormals = this.getFacetLocalNormals();
  21308. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21309. if (!facetsInBlock) {
  21310. return null;
  21311. }
  21312. // Get the closest facet to (x, y, z)
  21313. var shortest = Number.MAX_VALUE; // init distance vars
  21314. var tmpDistance = shortest;
  21315. var fib; // current facet in the block
  21316. var norm; // current facet normal
  21317. var p0; // current facet barycenter position
  21318. // loop on all the facets in the current partitioning block
  21319. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21320. fib = facetsInBlock[idx];
  21321. norm = facetNormals[fib];
  21322. p0 = facetPositions[fib];
  21323. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21324. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21325. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21326. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21327. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21328. projx = x + norm.x * t0;
  21329. projy = y + norm.y * t0;
  21330. projz = z + norm.z * t0;
  21331. tmpx = projx - x;
  21332. tmpy = projy - y;
  21333. tmpz = projz - z;
  21334. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21335. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21336. shortest = tmpDistance;
  21337. closest = fib;
  21338. if (projected) {
  21339. projected.x = projx;
  21340. projected.y = projy;
  21341. projected.z = projz;
  21342. }
  21343. }
  21344. }
  21345. }
  21346. return closest;
  21347. };
  21348. /**
  21349. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21350. * @returns the parameters
  21351. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21352. */
  21353. AbstractMesh.prototype.getFacetDataParameters = function () {
  21354. return this._facetParameters;
  21355. };
  21356. /**
  21357. * Disables the feature FacetData and frees the related memory
  21358. * @returns the current mesh
  21359. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21360. */
  21361. AbstractMesh.prototype.disableFacetData = function () {
  21362. if (this._facetDataEnabled) {
  21363. this._facetDataEnabled = false;
  21364. this._facetPositions = new Array();
  21365. this._facetNormals = new Array();
  21366. this._facetPartitioning = new Array();
  21367. this._facetParameters = null;
  21368. this._depthSortedIndices = new Uint32Array(0);
  21369. }
  21370. return this;
  21371. };
  21372. /**
  21373. * Updates the AbstractMesh indices array
  21374. * @param indices defines the data source
  21375. * @returns the current mesh
  21376. */
  21377. AbstractMesh.prototype.updateIndices = function (indices) {
  21378. return this;
  21379. };
  21380. /**
  21381. * Creates new normals data for the mesh
  21382. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21383. * @returns the current mesh
  21384. */
  21385. AbstractMesh.prototype.createNormals = function (updatable) {
  21386. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21387. var indices = this.getIndices();
  21388. var normals;
  21389. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21390. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21391. }
  21392. else {
  21393. normals = [];
  21394. }
  21395. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21396. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21397. return this;
  21398. };
  21399. /**
  21400. * Align the mesh with a normal
  21401. * @param normal defines the normal to use
  21402. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21403. * @returns the current mesh
  21404. */
  21405. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21406. if (!upDirection) {
  21407. upDirection = BABYLON.Axis.Y;
  21408. }
  21409. var axisX = BABYLON.Tmp.Vector3[0];
  21410. var axisZ = BABYLON.Tmp.Vector3[1];
  21411. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21412. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21413. if (this.rotationQuaternion) {
  21414. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21415. }
  21416. else {
  21417. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21418. }
  21419. return this;
  21420. };
  21421. /** @hidden */
  21422. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21423. this._isOccluded = false;
  21424. };
  21425. /** No occlusion */
  21426. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21427. /** Occlusion set to optimisitic */
  21428. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21429. /** Occlusion set to strict */
  21430. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21431. /** Use an accurante occlusion algorithm */
  21432. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21433. /** Use a conservative occlusion algorithm */
  21434. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21435. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21436. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21437. /** Culling strategy with bounding sphere only and then frustum culling */
  21438. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21439. return AbstractMesh;
  21440. }(BABYLON.TransformNode));
  21441. BABYLON.AbstractMesh = AbstractMesh;
  21442. })(BABYLON || (BABYLON = {}));
  21443. //# sourceMappingURL=babylon.abstractMesh.js.map
  21444. var BABYLON;
  21445. (function (BABYLON) {
  21446. /**
  21447. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21448. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21449. * 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.
  21450. */
  21451. var Light = /** @class */ (function (_super) {
  21452. __extends(Light, _super);
  21453. /**
  21454. * Creates a Light object in the scene.
  21455. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21456. * @param name The firendly name of the light
  21457. * @param scene The scene the light belongs too
  21458. */
  21459. function Light(name, scene) {
  21460. var _this = _super.call(this, name, scene) || this;
  21461. /**
  21462. * Diffuse gives the basic color to an object.
  21463. */
  21464. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21465. /**
  21466. * Specular produces a highlight color on an object.
  21467. * Note: This is note affecting PBR materials.
  21468. */
  21469. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21470. /**
  21471. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21472. * falling off base on range or angle.
  21473. * This can be set to any values in Light.FALLOFF_x.
  21474. *
  21475. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21476. * other types of materials.
  21477. */
  21478. _this.falloffType = Light.FALLOFF_DEFAULT;
  21479. /**
  21480. * Strength of the light.
  21481. * Note: By default it is define in the framework own unit.
  21482. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21483. */
  21484. _this.intensity = 1.0;
  21485. _this._range = Number.MAX_VALUE;
  21486. _this._inverseSquaredRange = 0;
  21487. /**
  21488. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21489. * of light.
  21490. */
  21491. _this._photometricScale = 1.0;
  21492. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21493. _this._radius = 0.00001;
  21494. /**
  21495. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21496. * exceeding the number allowed of the materials.
  21497. */
  21498. _this.renderPriority = 0;
  21499. _this._shadowEnabled = true;
  21500. _this._excludeWithLayerMask = 0;
  21501. _this._includeOnlyWithLayerMask = 0;
  21502. _this._lightmapMode = 0;
  21503. /**
  21504. * @hidden Internal use only.
  21505. */
  21506. _this._excludedMeshesIds = new Array();
  21507. /**
  21508. * @hidden Internal use only.
  21509. */
  21510. _this._includedOnlyMeshesIds = new Array();
  21511. _this.getScene().addLight(_this);
  21512. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21513. _this._buildUniformLayout();
  21514. _this.includedOnlyMeshes = new Array();
  21515. _this.excludedMeshes = new Array();
  21516. _this._resyncMeshes();
  21517. return _this;
  21518. }
  21519. Object.defineProperty(Light.prototype, "range", {
  21520. /**
  21521. * Defines how far from the source the light is impacting in scene units.
  21522. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21523. */
  21524. get: function () {
  21525. return this._range;
  21526. },
  21527. /**
  21528. * Defines how far from the source the light is impacting in scene units.
  21529. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21530. */
  21531. set: function (value) {
  21532. this._range = value;
  21533. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21534. },
  21535. enumerable: true,
  21536. configurable: true
  21537. });
  21538. Object.defineProperty(Light.prototype, "intensityMode", {
  21539. /**
  21540. * Gets the photometric scale used to interpret the intensity.
  21541. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21542. */
  21543. get: function () {
  21544. return this._intensityMode;
  21545. },
  21546. /**
  21547. * Sets the photometric scale used to interpret the intensity.
  21548. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21549. */
  21550. set: function (value) {
  21551. this._intensityMode = value;
  21552. this._computePhotometricScale();
  21553. },
  21554. enumerable: true,
  21555. configurable: true
  21556. });
  21557. ;
  21558. ;
  21559. Object.defineProperty(Light.prototype, "radius", {
  21560. /**
  21561. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21562. */
  21563. get: function () {
  21564. return this._radius;
  21565. },
  21566. /**
  21567. * sets the light radius used by PBR Materials to simulate soft area lights.
  21568. */
  21569. set: function (value) {
  21570. this._radius = value;
  21571. this._computePhotometricScale();
  21572. },
  21573. enumerable: true,
  21574. configurable: true
  21575. });
  21576. ;
  21577. ;
  21578. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21579. /**
  21580. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21581. * the current shadow generator.
  21582. */
  21583. get: function () {
  21584. return this._shadowEnabled;
  21585. },
  21586. /**
  21587. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21588. * the current shadow generator.
  21589. */
  21590. set: function (value) {
  21591. if (this._shadowEnabled === value) {
  21592. return;
  21593. }
  21594. this._shadowEnabled = value;
  21595. this._markMeshesAsLightDirty();
  21596. },
  21597. enumerable: true,
  21598. configurable: true
  21599. });
  21600. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21601. /**
  21602. * Gets the only meshes impacted by this light.
  21603. */
  21604. get: function () {
  21605. return this._includedOnlyMeshes;
  21606. },
  21607. /**
  21608. * Sets the only meshes impacted by this light.
  21609. */
  21610. set: function (value) {
  21611. this._includedOnlyMeshes = value;
  21612. this._hookArrayForIncludedOnly(value);
  21613. },
  21614. enumerable: true,
  21615. configurable: true
  21616. });
  21617. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21618. /**
  21619. * Gets the meshes not impacted by this light.
  21620. */
  21621. get: function () {
  21622. return this._excludedMeshes;
  21623. },
  21624. /**
  21625. * Sets the meshes not impacted by this light.
  21626. */
  21627. set: function (value) {
  21628. this._excludedMeshes = value;
  21629. this._hookArrayForExcluded(value);
  21630. },
  21631. enumerable: true,
  21632. configurable: true
  21633. });
  21634. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21635. /**
  21636. * Gets the layer id use to find what meshes are not impacted by the light.
  21637. * Inactive if 0
  21638. */
  21639. get: function () {
  21640. return this._excludeWithLayerMask;
  21641. },
  21642. /**
  21643. * Sets the layer id use to find what meshes are not impacted by the light.
  21644. * Inactive if 0
  21645. */
  21646. set: function (value) {
  21647. this._excludeWithLayerMask = value;
  21648. this._resyncMeshes();
  21649. },
  21650. enumerable: true,
  21651. configurable: true
  21652. });
  21653. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21654. /**
  21655. * Gets the layer id use to find what meshes are impacted by the light.
  21656. * Inactive if 0
  21657. */
  21658. get: function () {
  21659. return this._includeOnlyWithLayerMask;
  21660. },
  21661. /**
  21662. * Sets the layer id use to find what meshes are impacted by the light.
  21663. * Inactive if 0
  21664. */
  21665. set: function (value) {
  21666. this._includeOnlyWithLayerMask = value;
  21667. this._resyncMeshes();
  21668. },
  21669. enumerable: true,
  21670. configurable: true
  21671. });
  21672. Object.defineProperty(Light.prototype, "lightmapMode", {
  21673. /**
  21674. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21675. */
  21676. get: function () {
  21677. return this._lightmapMode;
  21678. },
  21679. /**
  21680. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21681. */
  21682. set: function (value) {
  21683. if (this._lightmapMode === value) {
  21684. return;
  21685. }
  21686. this._lightmapMode = value;
  21687. this._markMeshesAsLightDirty();
  21688. },
  21689. enumerable: true,
  21690. configurable: true
  21691. });
  21692. /**
  21693. * Returns the string "Light".
  21694. * @returns the class name
  21695. */
  21696. Light.prototype.getClassName = function () {
  21697. return "Light";
  21698. };
  21699. /**
  21700. * Converts the light information to a readable string for debug purpose.
  21701. * @param fullDetails Supports for multiple levels of logging within scene loading
  21702. * @returns the human readable light info
  21703. */
  21704. Light.prototype.toString = function (fullDetails) {
  21705. var ret = "Name: " + this.name;
  21706. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21707. if (this.animations) {
  21708. for (var i = 0; i < this.animations.length; i++) {
  21709. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21710. }
  21711. }
  21712. if (fullDetails) {
  21713. }
  21714. return ret;
  21715. };
  21716. /**
  21717. * Set the enabled state of this node.
  21718. * @param value - the new enabled state
  21719. */
  21720. Light.prototype.setEnabled = function (value) {
  21721. _super.prototype.setEnabled.call(this, value);
  21722. this._resyncMeshes();
  21723. };
  21724. /**
  21725. * Returns the Light associated shadow generator if any.
  21726. * @return the associated shadow generator.
  21727. */
  21728. Light.prototype.getShadowGenerator = function () {
  21729. return this._shadowGenerator;
  21730. };
  21731. /**
  21732. * Returns a Vector3, the absolute light position in the World.
  21733. * @returns the world space position of the light
  21734. */
  21735. Light.prototype.getAbsolutePosition = function () {
  21736. return BABYLON.Vector3.Zero();
  21737. };
  21738. /**
  21739. * Specifies if the light will affect the passed mesh.
  21740. * @param mesh The mesh to test against the light
  21741. * @return true the mesh is affected otherwise, false.
  21742. */
  21743. Light.prototype.canAffectMesh = function (mesh) {
  21744. if (!mesh) {
  21745. return true;
  21746. }
  21747. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21748. return false;
  21749. }
  21750. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21751. return false;
  21752. }
  21753. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21754. return false;
  21755. }
  21756. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21757. return false;
  21758. }
  21759. return true;
  21760. };
  21761. /**
  21762. * Computes and Returns the light World matrix.
  21763. * @returns the world matrix
  21764. */
  21765. Light.prototype.getWorldMatrix = function () {
  21766. this._currentRenderId = this.getScene().getRenderId();
  21767. this._childRenderId = this._currentRenderId;
  21768. var worldMatrix = this._getWorldMatrix();
  21769. if (this.parent && this.parent.getWorldMatrix) {
  21770. if (!this._parentedWorldMatrix) {
  21771. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21772. }
  21773. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21774. this._markSyncedWithParent();
  21775. return this._parentedWorldMatrix;
  21776. }
  21777. return worldMatrix;
  21778. };
  21779. /**
  21780. * Sort function to order lights for rendering.
  21781. * @param a First Light object to compare to second.
  21782. * @param b Second Light object to compare first.
  21783. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21784. */
  21785. Light.CompareLightsPriority = function (a, b) {
  21786. //shadow-casting lights have priority over non-shadow-casting lights
  21787. //the renderPrioirty is a secondary sort criterion
  21788. if (a.shadowEnabled !== b.shadowEnabled) {
  21789. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21790. }
  21791. return b.renderPriority - a.renderPriority;
  21792. };
  21793. /**
  21794. * Releases resources associated with this node.
  21795. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21796. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21797. */
  21798. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21799. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21800. if (this._shadowGenerator) {
  21801. this._shadowGenerator.dispose();
  21802. this._shadowGenerator = null;
  21803. }
  21804. // Animations
  21805. this.getScene().stopAnimation(this);
  21806. // Remove from meshes
  21807. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21808. var mesh = _a[_i];
  21809. mesh._removeLightSource(this);
  21810. }
  21811. this._uniformBuffer.dispose();
  21812. // Remove from scene
  21813. this.getScene().removeLight(this);
  21814. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21815. };
  21816. /**
  21817. * Returns the light type ID (integer).
  21818. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21819. */
  21820. Light.prototype.getTypeID = function () {
  21821. return 0;
  21822. };
  21823. /**
  21824. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21825. * @returns the scaled intensity in intensity mode unit
  21826. */
  21827. Light.prototype.getScaledIntensity = function () {
  21828. return this._photometricScale * this.intensity;
  21829. };
  21830. /**
  21831. * Returns a new Light object, named "name", from the current one.
  21832. * @param name The name of the cloned light
  21833. * @returns the new created light
  21834. */
  21835. Light.prototype.clone = function (name) {
  21836. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21837. if (!constructor) {
  21838. return null;
  21839. }
  21840. return BABYLON.SerializationHelper.Clone(constructor, this);
  21841. };
  21842. /**
  21843. * Serializes the current light into a Serialization object.
  21844. * @returns the serialized object.
  21845. */
  21846. Light.prototype.serialize = function () {
  21847. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21848. // Type
  21849. serializationObject.type = this.getTypeID();
  21850. // Parent
  21851. if (this.parent) {
  21852. serializationObject.parentId = this.parent.id;
  21853. }
  21854. // Inclusion / exclusions
  21855. if (this.excludedMeshes.length > 0) {
  21856. serializationObject.excludedMeshesIds = [];
  21857. this.excludedMeshes.forEach(function (mesh) {
  21858. serializationObject.excludedMeshesIds.push(mesh.id);
  21859. });
  21860. }
  21861. if (this.includedOnlyMeshes.length > 0) {
  21862. serializationObject.includedOnlyMeshesIds = [];
  21863. this.includedOnlyMeshes.forEach(function (mesh) {
  21864. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21865. });
  21866. }
  21867. // Animations
  21868. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21869. serializationObject.ranges = this.serializeAnimationRanges();
  21870. return serializationObject;
  21871. };
  21872. /**
  21873. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21874. * This new light is named "name" and added to the passed scene.
  21875. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21876. * @param name The friendly name of the light
  21877. * @param scene The scene the new light will belong to
  21878. * @returns the constructor function
  21879. */
  21880. Light.GetConstructorFromName = function (type, name, scene) {
  21881. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21882. if (constructorFunc) {
  21883. return constructorFunc;
  21884. }
  21885. // Default to no light for none present once.
  21886. return null;
  21887. };
  21888. /**
  21889. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21890. * @param parsedLight The JSON representation of the light
  21891. * @param scene The scene to create the parsed light in
  21892. * @returns the created light after parsing
  21893. */
  21894. Light.Parse = function (parsedLight, scene) {
  21895. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21896. if (!constructor) {
  21897. return null;
  21898. }
  21899. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21900. // Inclusion / exclusions
  21901. if (parsedLight.excludedMeshesIds) {
  21902. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21903. }
  21904. if (parsedLight.includedOnlyMeshesIds) {
  21905. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21906. }
  21907. // Parent
  21908. if (parsedLight.parentId) {
  21909. light._waitingParentId = parsedLight.parentId;
  21910. }
  21911. // Animations
  21912. if (parsedLight.animations) {
  21913. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21914. var parsedAnimation = parsedLight.animations[animationIndex];
  21915. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21916. }
  21917. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21918. }
  21919. if (parsedLight.autoAnimate) {
  21920. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21921. }
  21922. return light;
  21923. };
  21924. Light.prototype._hookArrayForExcluded = function (array) {
  21925. var _this = this;
  21926. var oldPush = array.push;
  21927. array.push = function () {
  21928. var items = [];
  21929. for (var _i = 0; _i < arguments.length; _i++) {
  21930. items[_i] = arguments[_i];
  21931. }
  21932. var result = oldPush.apply(array, items);
  21933. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21934. var item = items_1[_a];
  21935. item._resyncLighSource(_this);
  21936. }
  21937. return result;
  21938. };
  21939. var oldSplice = array.splice;
  21940. array.splice = function (index, deleteCount) {
  21941. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21942. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21943. var item = deleted_1[_i];
  21944. item._resyncLighSource(_this);
  21945. }
  21946. return deleted;
  21947. };
  21948. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21949. var item = array_1[_i];
  21950. item._resyncLighSource(this);
  21951. }
  21952. };
  21953. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21954. var _this = this;
  21955. var oldPush = array.push;
  21956. array.push = function () {
  21957. var items = [];
  21958. for (var _i = 0; _i < arguments.length; _i++) {
  21959. items[_i] = arguments[_i];
  21960. }
  21961. var result = oldPush.apply(array, items);
  21962. _this._resyncMeshes();
  21963. return result;
  21964. };
  21965. var oldSplice = array.splice;
  21966. array.splice = function (index, deleteCount) {
  21967. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21968. _this._resyncMeshes();
  21969. return deleted;
  21970. };
  21971. this._resyncMeshes();
  21972. };
  21973. Light.prototype._resyncMeshes = function () {
  21974. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21975. var mesh = _a[_i];
  21976. mesh._resyncLighSource(this);
  21977. }
  21978. };
  21979. /**
  21980. * Forces the meshes to update their light related information in their rendering used effects
  21981. * @hidden Internal Use Only
  21982. */
  21983. Light.prototype._markMeshesAsLightDirty = function () {
  21984. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21985. var mesh = _a[_i];
  21986. if (mesh._lightSources.indexOf(this) !== -1) {
  21987. mesh._markSubMeshesAsLightDirty();
  21988. }
  21989. }
  21990. };
  21991. /**
  21992. * Recomputes the cached photometric scale if needed.
  21993. */
  21994. Light.prototype._computePhotometricScale = function () {
  21995. this._photometricScale = this._getPhotometricScale();
  21996. this.getScene().resetCachedMaterial();
  21997. };
  21998. /**
  21999. * Returns the Photometric Scale according to the light type and intensity mode.
  22000. */
  22001. Light.prototype._getPhotometricScale = function () {
  22002. var photometricScale = 0.0;
  22003. var lightTypeID = this.getTypeID();
  22004. //get photometric mode
  22005. var photometricMode = this.intensityMode;
  22006. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22007. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22008. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22009. }
  22010. else {
  22011. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22012. }
  22013. }
  22014. //compute photometric scale
  22015. switch (lightTypeID) {
  22016. case Light.LIGHTTYPEID_POINTLIGHT:
  22017. case Light.LIGHTTYPEID_SPOTLIGHT:
  22018. switch (photometricMode) {
  22019. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22020. photometricScale = 1.0 / (4.0 * Math.PI);
  22021. break;
  22022. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22023. photometricScale = 1.0;
  22024. break;
  22025. case Light.INTENSITYMODE_LUMINANCE:
  22026. photometricScale = this.radius * this.radius;
  22027. break;
  22028. }
  22029. break;
  22030. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22031. switch (photometricMode) {
  22032. case Light.INTENSITYMODE_ILLUMINANCE:
  22033. photometricScale = 1.0;
  22034. break;
  22035. case Light.INTENSITYMODE_LUMINANCE:
  22036. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22037. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22038. var apexAngleRadians = this.radius;
  22039. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22040. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22041. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22042. photometricScale = solidAngle;
  22043. break;
  22044. }
  22045. break;
  22046. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22047. // No fall off in hemisperic light.
  22048. photometricScale = 1.0;
  22049. break;
  22050. }
  22051. return photometricScale;
  22052. };
  22053. /**
  22054. * Reorder the light in the scene according to their defined priority.
  22055. * @hidden Internal Use Only
  22056. */
  22057. Light.prototype._reorderLightsInScene = function () {
  22058. var scene = this.getScene();
  22059. if (this._renderPriority != 0) {
  22060. scene.requireLightSorting = true;
  22061. }
  22062. this.getScene().sortLightsByPriority();
  22063. };
  22064. /**
  22065. * Falloff Default: light is falling off following the material specification:
  22066. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22067. */
  22068. Light.FALLOFF_DEFAULT = 0;
  22069. /**
  22070. * Falloff Physical: light is falling off following the inverse squared distance law.
  22071. */
  22072. Light.FALLOFF_PHYSICAL = 1;
  22073. /**
  22074. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22075. * to enhance interoperability with other engines.
  22076. */
  22077. Light.FALLOFF_GLTF = 2;
  22078. /**
  22079. * Falloff Standard: light is falling off like in the standard material
  22080. * to enhance interoperability with other materials.
  22081. */
  22082. Light.FALLOFF_STANDARD = 3;
  22083. //lightmapMode Consts
  22084. /**
  22085. * If every light affecting the material is in this lightmapMode,
  22086. * material.lightmapTexture adds or multiplies
  22087. * (depends on material.useLightmapAsShadowmap)
  22088. * after every other light calculations.
  22089. */
  22090. Light.LIGHTMAP_DEFAULT = 0;
  22091. /**
  22092. * material.lightmapTexture as only diffuse lighting from this light
  22093. * adds only specular lighting from this light
  22094. * adds dynamic shadows
  22095. */
  22096. Light.LIGHTMAP_SPECULAR = 1;
  22097. /**
  22098. * material.lightmapTexture as only lighting
  22099. * no light calculation from this light
  22100. * only adds dynamic shadows from this light
  22101. */
  22102. Light.LIGHTMAP_SHADOWSONLY = 2;
  22103. // Intensity Mode Consts
  22104. /**
  22105. * Each light type uses the default quantity according to its type:
  22106. * point/spot lights use luminous intensity
  22107. * directional lights use illuminance
  22108. */
  22109. Light.INTENSITYMODE_AUTOMATIC = 0;
  22110. /**
  22111. * lumen (lm)
  22112. */
  22113. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22114. /**
  22115. * candela (lm/sr)
  22116. */
  22117. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22118. /**
  22119. * lux (lm/m^2)
  22120. */
  22121. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22122. /**
  22123. * nit (cd/m^2)
  22124. */
  22125. Light.INTENSITYMODE_LUMINANCE = 4;
  22126. // Light types ids const.
  22127. /**
  22128. * Light type const id of the point light.
  22129. */
  22130. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22131. /**
  22132. * Light type const id of the directional light.
  22133. */
  22134. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22135. /**
  22136. * Light type const id of the spot light.
  22137. */
  22138. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22139. /**
  22140. * Light type const id of the hemispheric light.
  22141. */
  22142. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22143. __decorate([
  22144. BABYLON.serializeAsColor3()
  22145. ], Light.prototype, "diffuse", void 0);
  22146. __decorate([
  22147. BABYLON.serializeAsColor3()
  22148. ], Light.prototype, "specular", void 0);
  22149. __decorate([
  22150. BABYLON.serialize()
  22151. ], Light.prototype, "falloffType", void 0);
  22152. __decorate([
  22153. BABYLON.serialize()
  22154. ], Light.prototype, "intensity", void 0);
  22155. __decorate([
  22156. BABYLON.serialize()
  22157. ], Light.prototype, "range", null);
  22158. __decorate([
  22159. BABYLON.serialize()
  22160. ], Light.prototype, "intensityMode", null);
  22161. __decorate([
  22162. BABYLON.serialize()
  22163. ], Light.prototype, "radius", null);
  22164. __decorate([
  22165. BABYLON.serialize()
  22166. ], Light.prototype, "_renderPriority", void 0);
  22167. __decorate([
  22168. BABYLON.expandToProperty("_reorderLightsInScene")
  22169. ], Light.prototype, "renderPriority", void 0);
  22170. __decorate([
  22171. BABYLON.serialize("shadowEnabled")
  22172. ], Light.prototype, "_shadowEnabled", void 0);
  22173. __decorate([
  22174. BABYLON.serialize("excludeWithLayerMask")
  22175. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22176. __decorate([
  22177. BABYLON.serialize("includeOnlyWithLayerMask")
  22178. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22179. __decorate([
  22180. BABYLON.serialize("lightmapMode")
  22181. ], Light.prototype, "_lightmapMode", void 0);
  22182. return Light;
  22183. }(BABYLON.Node));
  22184. BABYLON.Light = Light;
  22185. })(BABYLON || (BABYLON = {}));
  22186. //# sourceMappingURL=babylon.light.js.map
  22187. var BABYLON;
  22188. (function (BABYLON) {
  22189. var Camera = /** @class */ (function (_super) {
  22190. __extends(Camera, _super);
  22191. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22192. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22193. var _this = _super.call(this, name, scene) || this;
  22194. /**
  22195. * The vector the camera should consider as up.
  22196. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22197. */
  22198. _this.upVector = BABYLON.Vector3.Up();
  22199. _this.orthoLeft = null;
  22200. _this.orthoRight = null;
  22201. _this.orthoBottom = null;
  22202. _this.orthoTop = null;
  22203. /**
  22204. * FOV is set in Radians. (default is 0.8)
  22205. */
  22206. _this.fov = 0.8;
  22207. _this.minZ = 1;
  22208. _this.maxZ = 10000.0;
  22209. _this.inertia = 0.9;
  22210. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22211. _this.isIntermediate = false;
  22212. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22213. /**
  22214. * Restricts the camera to viewing objects with the same layerMask.
  22215. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22216. */
  22217. _this.layerMask = 0x0FFFFFFF;
  22218. /**
  22219. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22220. */
  22221. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22222. // Camera rig members
  22223. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22224. /** @hidden */
  22225. _this._rigCameras = new Array();
  22226. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22227. /** @hidden */
  22228. _this._skipRendering = false;
  22229. _this.customRenderTargets = new Array();
  22230. // Observables
  22231. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22232. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22233. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22234. _this.onRestoreStateObservable = new BABYLON.Observable();
  22235. // Cache
  22236. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22237. _this._projectionMatrix = new BABYLON.Matrix();
  22238. _this._doNotComputeProjectionMatrix = false;
  22239. _this._worldMatrix = BABYLON.Matrix.Identity();
  22240. _this._postProcesses = new Array();
  22241. _this._transformMatrix = BABYLON.Matrix.Zero();
  22242. _this._activeMeshes = new BABYLON.SmartArray(256);
  22243. _this._globalPosition = BABYLON.Vector3.Zero();
  22244. _this._refreshFrustumPlanes = true;
  22245. _this.getScene().addCamera(_this);
  22246. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22247. _this.getScene().activeCamera = _this;
  22248. }
  22249. _this.position = position;
  22250. return _this;
  22251. }
  22252. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22253. get: function () {
  22254. return Camera._PERSPECTIVE_CAMERA;
  22255. },
  22256. enumerable: true,
  22257. configurable: true
  22258. });
  22259. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22260. get: function () {
  22261. return Camera._ORTHOGRAPHIC_CAMERA;
  22262. },
  22263. enumerable: true,
  22264. configurable: true
  22265. });
  22266. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22267. /**
  22268. * This is the default FOV mode for perspective cameras.
  22269. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22270. *
  22271. */
  22272. get: function () {
  22273. return Camera._FOVMODE_VERTICAL_FIXED;
  22274. },
  22275. enumerable: true,
  22276. configurable: true
  22277. });
  22278. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22279. /**
  22280. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22281. *
  22282. */
  22283. get: function () {
  22284. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22285. },
  22286. enumerable: true,
  22287. configurable: true
  22288. });
  22289. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22290. get: function () {
  22291. return Camera._RIG_MODE_NONE;
  22292. },
  22293. enumerable: true,
  22294. configurable: true
  22295. });
  22296. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22297. get: function () {
  22298. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22299. },
  22300. enumerable: true,
  22301. configurable: true
  22302. });
  22303. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22304. get: function () {
  22305. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22306. },
  22307. enumerable: true,
  22308. configurable: true
  22309. });
  22310. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22311. get: function () {
  22312. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22313. },
  22314. enumerable: true,
  22315. configurable: true
  22316. });
  22317. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22318. get: function () {
  22319. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22320. },
  22321. enumerable: true,
  22322. configurable: true
  22323. });
  22324. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22325. get: function () {
  22326. return Camera._RIG_MODE_VR;
  22327. },
  22328. enumerable: true,
  22329. configurable: true
  22330. });
  22331. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22332. get: function () {
  22333. return Camera._RIG_MODE_WEBVR;
  22334. },
  22335. enumerable: true,
  22336. configurable: true
  22337. });
  22338. /**
  22339. * Store current camera state (fov, position, etc..)
  22340. */
  22341. Camera.prototype.storeState = function () {
  22342. this._stateStored = true;
  22343. this._storedFov = this.fov;
  22344. return this;
  22345. };
  22346. /**
  22347. * Restores the camera state values if it has been stored. You must call storeState() first
  22348. */
  22349. Camera.prototype._restoreStateValues = function () {
  22350. if (!this._stateStored) {
  22351. return false;
  22352. }
  22353. this.fov = this._storedFov;
  22354. return true;
  22355. };
  22356. /**
  22357. * Restored camera state. You must call storeState() first
  22358. */
  22359. Camera.prototype.restoreState = function () {
  22360. if (this._restoreStateValues()) {
  22361. this.onRestoreStateObservable.notifyObservers(this);
  22362. return true;
  22363. }
  22364. return false;
  22365. };
  22366. Camera.prototype.getClassName = function () {
  22367. return "Camera";
  22368. };
  22369. /**
  22370. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22371. */
  22372. Camera.prototype.toString = function (fullDetails) {
  22373. var ret = "Name: " + this.name;
  22374. ret += ", type: " + this.getClassName();
  22375. if (this.animations) {
  22376. for (var i = 0; i < this.animations.length; i++) {
  22377. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22378. }
  22379. }
  22380. if (fullDetails) {
  22381. }
  22382. return ret;
  22383. };
  22384. Object.defineProperty(Camera.prototype, "globalPosition", {
  22385. get: function () {
  22386. return this._globalPosition;
  22387. },
  22388. enumerable: true,
  22389. configurable: true
  22390. });
  22391. Camera.prototype.getActiveMeshes = function () {
  22392. return this._activeMeshes;
  22393. };
  22394. Camera.prototype.isActiveMesh = function (mesh) {
  22395. return (this._activeMeshes.indexOf(mesh) !== -1);
  22396. };
  22397. /**
  22398. * Is this camera ready to be used/rendered
  22399. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22400. * @return true if the camera is ready
  22401. */
  22402. Camera.prototype.isReady = function (completeCheck) {
  22403. if (completeCheck === void 0) { completeCheck = false; }
  22404. if (completeCheck) {
  22405. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22406. var pp = _a[_i];
  22407. if (pp && !pp.isReady()) {
  22408. return false;
  22409. }
  22410. }
  22411. }
  22412. return _super.prototype.isReady.call(this, completeCheck);
  22413. };
  22414. //Cache
  22415. /** @hidden */
  22416. Camera.prototype._initCache = function () {
  22417. _super.prototype._initCache.call(this);
  22418. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22419. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22420. this._cache.mode = undefined;
  22421. this._cache.minZ = undefined;
  22422. this._cache.maxZ = undefined;
  22423. this._cache.fov = undefined;
  22424. this._cache.fovMode = undefined;
  22425. this._cache.aspectRatio = undefined;
  22426. this._cache.orthoLeft = undefined;
  22427. this._cache.orthoRight = undefined;
  22428. this._cache.orthoBottom = undefined;
  22429. this._cache.orthoTop = undefined;
  22430. this._cache.renderWidth = undefined;
  22431. this._cache.renderHeight = undefined;
  22432. };
  22433. /** @hidden */
  22434. Camera.prototype._updateCache = function (ignoreParentClass) {
  22435. if (!ignoreParentClass) {
  22436. _super.prototype._updateCache.call(this);
  22437. }
  22438. this._cache.position.copyFrom(this.position);
  22439. this._cache.upVector.copyFrom(this.upVector);
  22440. };
  22441. // Synchronized
  22442. /** @hidden */
  22443. Camera.prototype._isSynchronized = function () {
  22444. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22445. };
  22446. /** @hidden */
  22447. Camera.prototype._isSynchronizedViewMatrix = function () {
  22448. if (!_super.prototype._isSynchronized.call(this))
  22449. return false;
  22450. return this._cache.position.equals(this.position)
  22451. && this._cache.upVector.equals(this.upVector)
  22452. && this.isSynchronizedWithParent();
  22453. };
  22454. /** @hidden */
  22455. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22456. var check = this._cache.mode === this.mode
  22457. && this._cache.minZ === this.minZ
  22458. && this._cache.maxZ === this.maxZ;
  22459. if (!check) {
  22460. return false;
  22461. }
  22462. var engine = this.getEngine();
  22463. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22464. check = this._cache.fov === this.fov
  22465. && this._cache.fovMode === this.fovMode
  22466. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22467. }
  22468. else {
  22469. check = this._cache.orthoLeft === this.orthoLeft
  22470. && this._cache.orthoRight === this.orthoRight
  22471. && this._cache.orthoBottom === this.orthoBottom
  22472. && this._cache.orthoTop === this.orthoTop
  22473. && this._cache.renderWidth === engine.getRenderWidth()
  22474. && this._cache.renderHeight === engine.getRenderHeight();
  22475. }
  22476. return check;
  22477. };
  22478. // Controls
  22479. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22480. };
  22481. Camera.prototype.detachControl = function (element) {
  22482. };
  22483. Camera.prototype.update = function () {
  22484. this._checkInputs();
  22485. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22486. this._updateRigCameras();
  22487. }
  22488. };
  22489. /** @hidden */
  22490. Camera.prototype._checkInputs = function () {
  22491. this.onAfterCheckInputsObservable.notifyObservers(this);
  22492. };
  22493. Object.defineProperty(Camera.prototype, "rigCameras", {
  22494. get: function () {
  22495. return this._rigCameras;
  22496. },
  22497. enumerable: true,
  22498. configurable: true
  22499. });
  22500. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22501. get: function () {
  22502. return this._rigPostProcess;
  22503. },
  22504. enumerable: true,
  22505. configurable: true
  22506. });
  22507. /**
  22508. * Internal, gets the first post proces.
  22509. * @returns the first post process to be run on this camera.
  22510. */
  22511. Camera.prototype._getFirstPostProcess = function () {
  22512. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22513. if (this._postProcesses[ppIndex] !== null) {
  22514. return this._postProcesses[ppIndex];
  22515. }
  22516. }
  22517. return null;
  22518. };
  22519. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22520. // invalidate framebuffer
  22521. var firstPostProcess = this._getFirstPostProcess();
  22522. if (firstPostProcess) {
  22523. firstPostProcess.markTextureDirty();
  22524. }
  22525. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22526. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22527. var cam = this._rigCameras[i];
  22528. var rigPostProcess = cam._rigPostProcess;
  22529. // for VR rig, there does not have to be a post process
  22530. if (rigPostProcess) {
  22531. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22532. if (isPass) {
  22533. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22534. cam.isIntermediate = this._postProcesses.length === 0;
  22535. }
  22536. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22537. rigPostProcess.markTextureDirty();
  22538. }
  22539. else {
  22540. cam._postProcesses = this._postProcesses.slice(0);
  22541. }
  22542. }
  22543. };
  22544. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22545. if (insertAt === void 0) { insertAt = null; }
  22546. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22547. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22548. return 0;
  22549. }
  22550. if (insertAt == null || insertAt < 0) {
  22551. this._postProcesses.push(postProcess);
  22552. }
  22553. else if (this._postProcesses[insertAt] === null) {
  22554. this._postProcesses[insertAt] = postProcess;
  22555. }
  22556. else {
  22557. this._postProcesses.splice(insertAt, 0, postProcess);
  22558. }
  22559. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22560. return this._postProcesses.indexOf(postProcess);
  22561. };
  22562. Camera.prototype.detachPostProcess = function (postProcess) {
  22563. var idx = this._postProcesses.indexOf(postProcess);
  22564. if (idx !== -1) {
  22565. this._postProcesses[idx] = null;
  22566. }
  22567. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22568. };
  22569. Camera.prototype.getWorldMatrix = function () {
  22570. if (this._isSynchronizedViewMatrix()) {
  22571. return this._worldMatrix;
  22572. }
  22573. // Getting the the view matrix will also compute the world matrix.
  22574. this.getViewMatrix();
  22575. return this._worldMatrix;
  22576. };
  22577. /** @hidden */
  22578. Camera.prototype._getViewMatrix = function () {
  22579. return BABYLON.Matrix.Identity();
  22580. };
  22581. Camera.prototype.getViewMatrix = function (force) {
  22582. if (!force && this._isSynchronizedViewMatrix()) {
  22583. return this._computedViewMatrix;
  22584. }
  22585. this.updateCache();
  22586. this._computedViewMatrix = this._getViewMatrix();
  22587. this._currentRenderId = this.getScene().getRenderId();
  22588. this._childRenderId = this._currentRenderId;
  22589. this._refreshFrustumPlanes = true;
  22590. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22591. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22592. }
  22593. this.onViewMatrixChangedObservable.notifyObservers(this);
  22594. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22595. return this._computedViewMatrix;
  22596. };
  22597. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22598. this._doNotComputeProjectionMatrix = true;
  22599. if (projection !== undefined) {
  22600. this._projectionMatrix = projection;
  22601. }
  22602. };
  22603. ;
  22604. Camera.prototype.unfreezeProjectionMatrix = function () {
  22605. this._doNotComputeProjectionMatrix = false;
  22606. };
  22607. ;
  22608. Camera.prototype.getProjectionMatrix = function (force) {
  22609. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22610. return this._projectionMatrix;
  22611. }
  22612. // Cache
  22613. this._cache.mode = this.mode;
  22614. this._cache.minZ = this.minZ;
  22615. this._cache.maxZ = this.maxZ;
  22616. // Matrix
  22617. this._refreshFrustumPlanes = true;
  22618. var engine = this.getEngine();
  22619. var scene = this.getScene();
  22620. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22621. this._cache.fov = this.fov;
  22622. this._cache.fovMode = this.fovMode;
  22623. this._cache.aspectRatio = engine.getAspectRatio(this);
  22624. if (this.minZ <= 0) {
  22625. this.minZ = 0.1;
  22626. }
  22627. if (scene.useRightHandedSystem) {
  22628. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22629. }
  22630. else {
  22631. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22632. }
  22633. }
  22634. else {
  22635. var halfWidth = engine.getRenderWidth() / 2.0;
  22636. var halfHeight = engine.getRenderHeight() / 2.0;
  22637. if (scene.useRightHandedSystem) {
  22638. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22639. }
  22640. else {
  22641. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22642. }
  22643. this._cache.orthoLeft = this.orthoLeft;
  22644. this._cache.orthoRight = this.orthoRight;
  22645. this._cache.orthoBottom = this.orthoBottom;
  22646. this._cache.orthoTop = this.orthoTop;
  22647. this._cache.renderWidth = engine.getRenderWidth();
  22648. this._cache.renderHeight = engine.getRenderHeight();
  22649. }
  22650. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22651. return this._projectionMatrix;
  22652. };
  22653. /**
  22654. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22655. * @returns a Matrix
  22656. */
  22657. Camera.prototype.getTransformationMatrix = function () {
  22658. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22659. return this._transformMatrix;
  22660. };
  22661. Camera.prototype.updateFrustumPlanes = function () {
  22662. if (!this._refreshFrustumPlanes) {
  22663. return;
  22664. }
  22665. this.getTransformationMatrix();
  22666. if (!this._frustumPlanes) {
  22667. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22668. }
  22669. else {
  22670. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22671. }
  22672. this._refreshFrustumPlanes = false;
  22673. };
  22674. Camera.prototype.isInFrustum = function (target) {
  22675. this.updateFrustumPlanes();
  22676. return target.isInFrustum(this._frustumPlanes);
  22677. };
  22678. Camera.prototype.isCompletelyInFrustum = function (target) {
  22679. this.updateFrustumPlanes();
  22680. return target.isCompletelyInFrustum(this._frustumPlanes);
  22681. };
  22682. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22683. if (length === void 0) { length = 100; }
  22684. if (!transform) {
  22685. transform = this.getWorldMatrix();
  22686. }
  22687. if (!origin) {
  22688. origin = this.position;
  22689. }
  22690. var forward = new BABYLON.Vector3(0, 0, 1);
  22691. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22692. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22693. return new BABYLON.Ray(origin, direction, length);
  22694. };
  22695. /**
  22696. * Releases resources associated with this node.
  22697. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22698. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22699. */
  22700. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22701. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22702. // Observables
  22703. this.onViewMatrixChangedObservable.clear();
  22704. this.onProjectionMatrixChangedObservable.clear();
  22705. this.onAfterCheckInputsObservable.clear();
  22706. this.onRestoreStateObservable.clear();
  22707. // Inputs
  22708. if (this.inputs) {
  22709. this.inputs.clear();
  22710. }
  22711. // Animations
  22712. this.getScene().stopAnimation(this);
  22713. // Remove from scene
  22714. this.getScene().removeCamera(this);
  22715. while (this._rigCameras.length > 0) {
  22716. var camera = this._rigCameras.pop();
  22717. if (camera) {
  22718. camera.dispose();
  22719. }
  22720. }
  22721. // Postprocesses
  22722. if (this._rigPostProcess) {
  22723. this._rigPostProcess.dispose(this);
  22724. this._rigPostProcess = null;
  22725. this._postProcesses = [];
  22726. }
  22727. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22728. this._rigPostProcess = null;
  22729. this._postProcesses = [];
  22730. }
  22731. else {
  22732. var i = this._postProcesses.length;
  22733. while (--i >= 0) {
  22734. var postProcess = this._postProcesses[i];
  22735. if (postProcess) {
  22736. postProcess.dispose(this);
  22737. }
  22738. }
  22739. }
  22740. // Render targets
  22741. var i = this.customRenderTargets.length;
  22742. while (--i >= 0) {
  22743. this.customRenderTargets[i].dispose();
  22744. }
  22745. this.customRenderTargets = [];
  22746. // Active Meshes
  22747. this._activeMeshes.dispose();
  22748. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22749. };
  22750. Object.defineProperty(Camera.prototype, "leftCamera", {
  22751. // ---- Camera rigs section ----
  22752. get: function () {
  22753. if (this._rigCameras.length < 1) {
  22754. return null;
  22755. }
  22756. return this._rigCameras[0];
  22757. },
  22758. enumerable: true,
  22759. configurable: true
  22760. });
  22761. Object.defineProperty(Camera.prototype, "rightCamera", {
  22762. get: function () {
  22763. if (this._rigCameras.length < 2) {
  22764. return null;
  22765. }
  22766. return this._rigCameras[1];
  22767. },
  22768. enumerable: true,
  22769. configurable: true
  22770. });
  22771. Camera.prototype.getLeftTarget = function () {
  22772. if (this._rigCameras.length < 1) {
  22773. return null;
  22774. }
  22775. return this._rigCameras[0].getTarget();
  22776. };
  22777. Camera.prototype.getRightTarget = function () {
  22778. if (this._rigCameras.length < 2) {
  22779. return null;
  22780. }
  22781. return this._rigCameras[1].getTarget();
  22782. };
  22783. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22784. if (this.cameraRigMode === mode) {
  22785. return;
  22786. }
  22787. while (this._rigCameras.length > 0) {
  22788. var camera = this._rigCameras.pop();
  22789. if (camera) {
  22790. camera.dispose();
  22791. }
  22792. }
  22793. this.cameraRigMode = mode;
  22794. this._cameraRigParams = {};
  22795. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22796. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22797. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22798. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22799. // create the rig cameras, unless none
  22800. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22801. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22802. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22803. if (leftCamera && rightCamera) {
  22804. this._rigCameras.push(leftCamera);
  22805. this._rigCameras.push(rightCamera);
  22806. }
  22807. }
  22808. switch (this.cameraRigMode) {
  22809. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22810. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22811. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22812. break;
  22813. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22814. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22815. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22816. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22817. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22818. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22819. break;
  22820. case Camera.RIG_MODE_VR:
  22821. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22822. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22823. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22824. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22825. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22826. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22827. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22828. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22829. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22830. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22831. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22832. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22833. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22834. if (metrics.compensateDistortion) {
  22835. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22836. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22837. }
  22838. break;
  22839. case Camera.RIG_MODE_WEBVR:
  22840. if (rigParams.vrDisplay) {
  22841. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22842. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22843. //Left eye
  22844. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22845. this._rigCameras[0].setCameraRigParameter("left", true);
  22846. //leaving this for future reference
  22847. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22848. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22849. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22850. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22851. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22852. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22853. this._rigCameras[0].parent = this;
  22854. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22855. //Right eye
  22856. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22857. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22858. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22859. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22860. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22861. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22862. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22863. this._rigCameras[1].parent = this;
  22864. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22865. if (Camera.UseAlternateWebVRRendering) {
  22866. this._rigCameras[1]._skipRendering = true;
  22867. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22868. }
  22869. }
  22870. break;
  22871. }
  22872. this._cascadePostProcessesToRigCams();
  22873. this.update();
  22874. };
  22875. Camera.prototype._getVRProjectionMatrix = function () {
  22876. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22877. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22878. return this._projectionMatrix;
  22879. };
  22880. Camera.prototype._updateCameraRotationMatrix = function () {
  22881. //Here for WebVR
  22882. };
  22883. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22884. //Here for WebVR
  22885. };
  22886. /**
  22887. * This function MUST be overwritten by the different WebVR cameras available.
  22888. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22889. */
  22890. Camera.prototype._getWebVRProjectionMatrix = function () {
  22891. return BABYLON.Matrix.Identity();
  22892. };
  22893. /**
  22894. * This function MUST be overwritten by the different WebVR cameras available.
  22895. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22896. */
  22897. Camera.prototype._getWebVRViewMatrix = function () {
  22898. return BABYLON.Matrix.Identity();
  22899. };
  22900. Camera.prototype.setCameraRigParameter = function (name, value) {
  22901. if (!this._cameraRigParams) {
  22902. this._cameraRigParams = {};
  22903. }
  22904. this._cameraRigParams[name] = value;
  22905. //provisionnally:
  22906. if (name === "interaxialDistance") {
  22907. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22908. }
  22909. };
  22910. /**
  22911. * needs to be overridden by children so sub has required properties to be copied
  22912. */
  22913. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22914. return null;
  22915. };
  22916. /**
  22917. * May need to be overridden by children
  22918. * @hidden
  22919. */
  22920. Camera.prototype._updateRigCameras = function () {
  22921. for (var i = 0; i < this._rigCameras.length; i++) {
  22922. this._rigCameras[i].minZ = this.minZ;
  22923. this._rigCameras[i].maxZ = this.maxZ;
  22924. this._rigCameras[i].fov = this.fov;
  22925. }
  22926. // only update viewport when ANAGLYPH
  22927. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22928. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22929. }
  22930. };
  22931. /** @hidden */
  22932. Camera.prototype._setupInputs = function () {
  22933. };
  22934. Camera.prototype.serialize = function () {
  22935. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22936. // Type
  22937. serializationObject.type = this.getClassName();
  22938. // Parent
  22939. if (this.parent) {
  22940. serializationObject.parentId = this.parent.id;
  22941. }
  22942. if (this.inputs) {
  22943. this.inputs.serialize(serializationObject);
  22944. }
  22945. // Animations
  22946. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22947. serializationObject.ranges = this.serializeAnimationRanges();
  22948. return serializationObject;
  22949. };
  22950. Camera.prototype.clone = function (name) {
  22951. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22952. };
  22953. Camera.prototype.getDirection = function (localAxis) {
  22954. var result = BABYLON.Vector3.Zero();
  22955. this.getDirectionToRef(localAxis, result);
  22956. return result;
  22957. };
  22958. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22959. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22960. };
  22961. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22962. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22963. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22964. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22965. interaxial_distance: interaxial_distance,
  22966. isStereoscopicSideBySide: isStereoscopicSideBySide
  22967. });
  22968. if (constructorFunc) {
  22969. return constructorFunc;
  22970. }
  22971. // Default to universal camera
  22972. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22973. };
  22974. Camera.prototype.computeWorldMatrix = function () {
  22975. return this.getWorldMatrix();
  22976. };
  22977. Camera.Parse = function (parsedCamera, scene) {
  22978. var type = parsedCamera.type;
  22979. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22980. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22981. // Parent
  22982. if (parsedCamera.parentId) {
  22983. camera._waitingParentId = parsedCamera.parentId;
  22984. }
  22985. //If camera has an input manager, let it parse inputs settings
  22986. if (camera.inputs) {
  22987. camera.inputs.parse(parsedCamera);
  22988. camera._setupInputs();
  22989. }
  22990. if (camera.setPosition) { // need to force position
  22991. camera.position.copyFromFloats(0, 0, 0);
  22992. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22993. }
  22994. // Target
  22995. if (parsedCamera.target) {
  22996. if (camera.setTarget) {
  22997. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22998. }
  22999. }
  23000. // Apply 3d rig, when found
  23001. if (parsedCamera.cameraRigMode) {
  23002. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23003. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23004. }
  23005. // Animations
  23006. if (parsedCamera.animations) {
  23007. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23008. var parsedAnimation = parsedCamera.animations[animationIndex];
  23009. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23010. }
  23011. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23012. }
  23013. if (parsedCamera.autoAnimate) {
  23014. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23015. }
  23016. return camera;
  23017. };
  23018. // Statics
  23019. Camera._PERSPECTIVE_CAMERA = 0;
  23020. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23021. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23022. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23023. Camera._RIG_MODE_NONE = 0;
  23024. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23025. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23026. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23027. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23028. Camera._RIG_MODE_VR = 20;
  23029. Camera._RIG_MODE_WEBVR = 21;
  23030. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23031. Camera.UseAlternateWebVRRendering = false;
  23032. __decorate([
  23033. BABYLON.serializeAsVector3()
  23034. ], Camera.prototype, "position", void 0);
  23035. __decorate([
  23036. BABYLON.serializeAsVector3()
  23037. ], Camera.prototype, "upVector", void 0);
  23038. __decorate([
  23039. BABYLON.serialize()
  23040. ], Camera.prototype, "orthoLeft", void 0);
  23041. __decorate([
  23042. BABYLON.serialize()
  23043. ], Camera.prototype, "orthoRight", void 0);
  23044. __decorate([
  23045. BABYLON.serialize()
  23046. ], Camera.prototype, "orthoBottom", void 0);
  23047. __decorate([
  23048. BABYLON.serialize()
  23049. ], Camera.prototype, "orthoTop", void 0);
  23050. __decorate([
  23051. BABYLON.serialize()
  23052. ], Camera.prototype, "fov", void 0);
  23053. __decorate([
  23054. BABYLON.serialize()
  23055. ], Camera.prototype, "minZ", void 0);
  23056. __decorate([
  23057. BABYLON.serialize()
  23058. ], Camera.prototype, "maxZ", void 0);
  23059. __decorate([
  23060. BABYLON.serialize()
  23061. ], Camera.prototype, "inertia", void 0);
  23062. __decorate([
  23063. BABYLON.serialize()
  23064. ], Camera.prototype, "mode", void 0);
  23065. __decorate([
  23066. BABYLON.serialize()
  23067. ], Camera.prototype, "layerMask", void 0);
  23068. __decorate([
  23069. BABYLON.serialize()
  23070. ], Camera.prototype, "fovMode", void 0);
  23071. __decorate([
  23072. BABYLON.serialize()
  23073. ], Camera.prototype, "cameraRigMode", void 0);
  23074. __decorate([
  23075. BABYLON.serialize()
  23076. ], Camera.prototype, "interaxialDistance", void 0);
  23077. __decorate([
  23078. BABYLON.serialize()
  23079. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23080. return Camera;
  23081. }(BABYLON.Node));
  23082. BABYLON.Camera = Camera;
  23083. })(BABYLON || (BABYLON = {}));
  23084. //# sourceMappingURL=babylon.camera.js.map
  23085. var BABYLON;
  23086. (function (BABYLON) {
  23087. var RenderingManager = /** @class */ (function () {
  23088. function RenderingManager(scene) {
  23089. /**
  23090. * @hidden
  23091. */
  23092. this._useSceneAutoClearSetup = false;
  23093. this._renderingGroups = new Array();
  23094. this._autoClearDepthStencil = {};
  23095. this._customOpaqueSortCompareFn = {};
  23096. this._customAlphaTestSortCompareFn = {};
  23097. this._customTransparentSortCompareFn = {};
  23098. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23099. this._scene = scene;
  23100. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23101. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23102. }
  23103. }
  23104. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23105. if (depth === void 0) { depth = true; }
  23106. if (stencil === void 0) { stencil = true; }
  23107. if (this._depthStencilBufferAlreadyCleaned) {
  23108. return;
  23109. }
  23110. this._scene.getEngine().clear(null, false, depth, stencil);
  23111. this._depthStencilBufferAlreadyCleaned = true;
  23112. };
  23113. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23114. // Update the observable context (not null as it only goes away on dispose)
  23115. var info = this._renderingGroupInfo;
  23116. info.scene = this._scene;
  23117. info.camera = this._scene.activeCamera;
  23118. // Dispatch sprites
  23119. if (renderSprites) {
  23120. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23121. var manager = this._scene.spriteManagers[index];
  23122. this.dispatchSprites(manager);
  23123. }
  23124. }
  23125. // Render
  23126. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23127. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23128. var renderingGroup = this._renderingGroups[index];
  23129. if (!renderingGroup)
  23130. continue;
  23131. var renderingGroupMask = Math.pow(2, index);
  23132. info.renderingGroupId = index;
  23133. // Before Observable
  23134. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23135. // Clear depth/stencil if needed
  23136. if (RenderingManager.AUTOCLEAR) {
  23137. var autoClear = this._useSceneAutoClearSetup ?
  23138. this._scene.getAutoClearDepthStencilSetup(index) :
  23139. this._autoClearDepthStencil[index];
  23140. if (autoClear && autoClear.autoClear) {
  23141. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23142. }
  23143. }
  23144. // Render
  23145. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23146. var step = _a[_i];
  23147. step.action(index);
  23148. }
  23149. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23150. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23151. var step = _c[_b];
  23152. step.action(index);
  23153. }
  23154. // After Observable
  23155. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23156. }
  23157. };
  23158. RenderingManager.prototype.reset = function () {
  23159. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23160. var renderingGroup = this._renderingGroups[index];
  23161. if (renderingGroup) {
  23162. renderingGroup.prepare();
  23163. }
  23164. }
  23165. };
  23166. RenderingManager.prototype.dispose = function () {
  23167. this.freeRenderingGroups();
  23168. this._renderingGroups.length = 0;
  23169. this._renderingGroupInfo = null;
  23170. };
  23171. /**
  23172. * Clear the info related to rendering groups preventing retention points during dispose.
  23173. */
  23174. RenderingManager.prototype.freeRenderingGroups = function () {
  23175. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23176. var renderingGroup = this._renderingGroups[index];
  23177. if (renderingGroup) {
  23178. renderingGroup.dispose();
  23179. }
  23180. }
  23181. };
  23182. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23183. if (this._renderingGroups[renderingGroupId] === undefined) {
  23184. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23185. }
  23186. };
  23187. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23188. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23189. this._prepareRenderingGroup(renderingGroupId);
  23190. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23191. };
  23192. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23193. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23194. this._prepareRenderingGroup(renderingGroupId);
  23195. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23196. };
  23197. /**
  23198. * @param subMesh The submesh to dispatch
  23199. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23200. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23201. */
  23202. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23203. if (mesh === undefined) {
  23204. mesh = subMesh.getMesh();
  23205. }
  23206. var renderingGroupId = mesh.renderingGroupId || 0;
  23207. this._prepareRenderingGroup(renderingGroupId);
  23208. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23209. };
  23210. /**
  23211. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23212. * This allowed control for front to back rendering or reversly depending of the special needs.
  23213. *
  23214. * @param renderingGroupId The rendering group id corresponding to its index
  23215. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23216. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23217. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23218. */
  23219. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23220. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23221. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23222. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23223. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23224. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23225. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23226. if (this._renderingGroups[renderingGroupId]) {
  23227. var group = this._renderingGroups[renderingGroupId];
  23228. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23229. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23230. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23231. }
  23232. };
  23233. /**
  23234. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23235. *
  23236. * @param renderingGroupId The rendering group id corresponding to its index
  23237. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23238. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23239. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23240. */
  23241. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23242. if (depth === void 0) { depth = true; }
  23243. if (stencil === void 0) { stencil = true; }
  23244. this._autoClearDepthStencil[renderingGroupId] = {
  23245. autoClear: autoClearDepthStencil,
  23246. depth: depth,
  23247. stencil: stencil
  23248. };
  23249. };
  23250. /**
  23251. * Gets the current auto clear configuration for one rendering group of the rendering
  23252. * manager.
  23253. * @param index the rendering group index to get the information for
  23254. * @returns The auto clear setup for the requested rendering group
  23255. */
  23256. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23257. return this._autoClearDepthStencil[index];
  23258. };
  23259. /**
  23260. * The max id used for rendering groups (not included)
  23261. */
  23262. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23263. /**
  23264. * The min id used for rendering groups (included)
  23265. */
  23266. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23267. /**
  23268. * Used to globally prevent autoclearing scenes.
  23269. */
  23270. RenderingManager.AUTOCLEAR = true;
  23271. return RenderingManager;
  23272. }());
  23273. BABYLON.RenderingManager = RenderingManager;
  23274. })(BABYLON || (BABYLON = {}));
  23275. //# sourceMappingURL=babylon.renderingManager.js.map
  23276. var BABYLON;
  23277. (function (BABYLON) {
  23278. var RenderingGroup = /** @class */ (function () {
  23279. /**
  23280. * Creates a new rendering group.
  23281. * @param index The rendering group index
  23282. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23283. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23284. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23285. */
  23286. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23287. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23288. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23289. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23290. this.index = index;
  23291. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23292. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23293. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23294. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23295. this._particleSystems = new BABYLON.SmartArray(256);
  23296. this._spriteManagers = new BABYLON.SmartArray(256);
  23297. this._edgesRenderers = new BABYLON.SmartArray(16);
  23298. this._scene = scene;
  23299. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23300. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23301. this.transparentSortCompareFn = transparentSortCompareFn;
  23302. }
  23303. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23304. /**
  23305. * Set the opaque sort comparison function.
  23306. * If null the sub meshes will be render in the order they were created
  23307. */
  23308. set: function (value) {
  23309. this._opaqueSortCompareFn = value;
  23310. if (value) {
  23311. this._renderOpaque = this.renderOpaqueSorted;
  23312. }
  23313. else {
  23314. this._renderOpaque = RenderingGroup.renderUnsorted;
  23315. }
  23316. },
  23317. enumerable: true,
  23318. configurable: true
  23319. });
  23320. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23321. /**
  23322. * Set the alpha test sort comparison function.
  23323. * If null the sub meshes will be render in the order they were created
  23324. */
  23325. set: function (value) {
  23326. this._alphaTestSortCompareFn = value;
  23327. if (value) {
  23328. this._renderAlphaTest = this.renderAlphaTestSorted;
  23329. }
  23330. else {
  23331. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23332. }
  23333. },
  23334. enumerable: true,
  23335. configurable: true
  23336. });
  23337. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23338. /**
  23339. * Set the transparent sort comparison function.
  23340. * If null the sub meshes will be render in the order they were created
  23341. */
  23342. set: function (value) {
  23343. if (value) {
  23344. this._transparentSortCompareFn = value;
  23345. }
  23346. else {
  23347. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23348. }
  23349. this._renderTransparent = this.renderTransparentSorted;
  23350. },
  23351. enumerable: true,
  23352. configurable: true
  23353. });
  23354. /**
  23355. * Render all the sub meshes contained in the group.
  23356. * @param customRenderFunction Used to override the default render behaviour of the group.
  23357. * @returns true if rendered some submeshes.
  23358. */
  23359. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23360. if (customRenderFunction) {
  23361. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23362. return;
  23363. }
  23364. var engine = this._scene.getEngine();
  23365. // Depth only
  23366. if (this._depthOnlySubMeshes.length !== 0) {
  23367. engine.setColorWrite(false);
  23368. this._renderAlphaTest(this._depthOnlySubMeshes);
  23369. engine.setColorWrite(true);
  23370. }
  23371. // Opaque
  23372. if (this._opaqueSubMeshes.length !== 0) {
  23373. this._renderOpaque(this._opaqueSubMeshes);
  23374. }
  23375. // Alpha test
  23376. if (this._alphaTestSubMeshes.length !== 0) {
  23377. this._renderAlphaTest(this._alphaTestSubMeshes);
  23378. }
  23379. var stencilState = engine.getStencilBuffer();
  23380. engine.setStencilBuffer(false);
  23381. // Sprites
  23382. if (renderSprites) {
  23383. this._renderSprites();
  23384. }
  23385. // Particles
  23386. if (renderParticles) {
  23387. this._renderParticles(activeMeshes);
  23388. }
  23389. if (this.onBeforeTransparentRendering) {
  23390. this.onBeforeTransparentRendering();
  23391. }
  23392. // Transparent
  23393. if (this._transparentSubMeshes.length !== 0) {
  23394. this._renderTransparent(this._transparentSubMeshes);
  23395. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23396. }
  23397. // Set back stencil to false in case it changes before the edge renderer.
  23398. engine.setStencilBuffer(false);
  23399. // Edges
  23400. if (this._edgesRenderers.length) {
  23401. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23402. this._edgesRenderers.data[edgesRendererIndex].render();
  23403. }
  23404. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23405. }
  23406. // Restore Stencil state.
  23407. engine.setStencilBuffer(stencilState);
  23408. };
  23409. /**
  23410. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23411. * @param subMeshes The submeshes to render
  23412. */
  23413. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23414. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23415. };
  23416. /**
  23417. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23418. * @param subMeshes The submeshes to render
  23419. */
  23420. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23421. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23422. };
  23423. /**
  23424. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23425. * @param subMeshes The submeshes to render
  23426. */
  23427. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23428. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23429. };
  23430. /**
  23431. * Renders the submeshes in a specified order.
  23432. * @param subMeshes The submeshes to sort before render
  23433. * @param sortCompareFn The comparison function use to sort
  23434. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23435. * @param transparent Specifies to activate blending if true
  23436. */
  23437. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23438. var subIndex = 0;
  23439. var subMesh;
  23440. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23441. for (; subIndex < subMeshes.length; subIndex++) {
  23442. subMesh = subMeshes.data[subIndex];
  23443. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23444. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23445. }
  23446. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23447. if (sortCompareFn) {
  23448. sortedArray.sort(sortCompareFn);
  23449. }
  23450. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23451. subMesh = sortedArray[subIndex];
  23452. if (transparent) {
  23453. var material = subMesh.getMaterial();
  23454. if (material && material.needDepthPrePass) {
  23455. var engine = material.getScene().getEngine();
  23456. engine.setColorWrite(false);
  23457. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23458. subMesh.render(false);
  23459. engine.setColorWrite(true);
  23460. }
  23461. }
  23462. subMesh.render(transparent);
  23463. }
  23464. };
  23465. /**
  23466. * Renders the submeshes in the order they were dispatched (no sort applied).
  23467. * @param subMeshes The submeshes to render
  23468. */
  23469. RenderingGroup.renderUnsorted = function (subMeshes) {
  23470. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23471. var submesh = subMeshes.data[subIndex];
  23472. submesh.render(false);
  23473. }
  23474. };
  23475. /**
  23476. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23477. * are rendered back to front if in the same alpha index.
  23478. *
  23479. * @param a The first submesh
  23480. * @param b The second submesh
  23481. * @returns The result of the comparison
  23482. */
  23483. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23484. // Alpha index first
  23485. if (a._alphaIndex > b._alphaIndex) {
  23486. return 1;
  23487. }
  23488. if (a._alphaIndex < b._alphaIndex) {
  23489. return -1;
  23490. }
  23491. // Then distance to camera
  23492. return RenderingGroup.backToFrontSortCompare(a, b);
  23493. };
  23494. /**
  23495. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23496. * are rendered back to front.
  23497. *
  23498. * @param a The first submesh
  23499. * @param b The second submesh
  23500. * @returns The result of the comparison
  23501. */
  23502. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23503. // Then distance to camera
  23504. if (a._distanceToCamera < b._distanceToCamera) {
  23505. return 1;
  23506. }
  23507. if (a._distanceToCamera > b._distanceToCamera) {
  23508. return -1;
  23509. }
  23510. return 0;
  23511. };
  23512. /**
  23513. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23514. * are rendered front to back (prevent overdraw).
  23515. *
  23516. * @param a The first submesh
  23517. * @param b The second submesh
  23518. * @returns The result of the comparison
  23519. */
  23520. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23521. // Then distance to camera
  23522. if (a._distanceToCamera < b._distanceToCamera) {
  23523. return -1;
  23524. }
  23525. if (a._distanceToCamera > b._distanceToCamera) {
  23526. return 1;
  23527. }
  23528. return 0;
  23529. };
  23530. /**
  23531. * Resets the different lists of submeshes to prepare a new frame.
  23532. */
  23533. RenderingGroup.prototype.prepare = function () {
  23534. this._opaqueSubMeshes.reset();
  23535. this._transparentSubMeshes.reset();
  23536. this._alphaTestSubMeshes.reset();
  23537. this._depthOnlySubMeshes.reset();
  23538. this._particleSystems.reset();
  23539. this._spriteManagers.reset();
  23540. this._edgesRenderers.reset();
  23541. };
  23542. RenderingGroup.prototype.dispose = function () {
  23543. this._opaqueSubMeshes.dispose();
  23544. this._transparentSubMeshes.dispose();
  23545. this._alphaTestSubMeshes.dispose();
  23546. this._depthOnlySubMeshes.dispose();
  23547. this._particleSystems.dispose();
  23548. this._spriteManagers.dispose();
  23549. this._edgesRenderers.dispose();
  23550. };
  23551. /**
  23552. * Inserts the submesh in its correct queue depending on its material.
  23553. * @param subMesh The submesh to dispatch
  23554. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23555. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23556. */
  23557. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23558. // Get mesh and materials if not provided
  23559. if (mesh === undefined) {
  23560. mesh = subMesh.getMesh();
  23561. }
  23562. if (material === undefined) {
  23563. material = subMesh.getMaterial();
  23564. }
  23565. if (material === null || material === undefined) {
  23566. return;
  23567. }
  23568. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23569. this._transparentSubMeshes.push(subMesh);
  23570. }
  23571. else if (material.needAlphaTesting()) { // Alpha test
  23572. if (material.needDepthPrePass) {
  23573. this._depthOnlySubMeshes.push(subMesh);
  23574. }
  23575. this._alphaTestSubMeshes.push(subMesh);
  23576. }
  23577. else {
  23578. if (material.needDepthPrePass) {
  23579. this._depthOnlySubMeshes.push(subMesh);
  23580. }
  23581. this._opaqueSubMeshes.push(subMesh); // Opaque
  23582. }
  23583. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23584. this._edgesRenderers.push(mesh._edgesRenderer);
  23585. }
  23586. };
  23587. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23588. this._spriteManagers.push(spriteManager);
  23589. };
  23590. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23591. this._particleSystems.push(particleSystem);
  23592. };
  23593. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23594. if (this._particleSystems.length === 0) {
  23595. return;
  23596. }
  23597. // Particles
  23598. var activeCamera = this._scene.activeCamera;
  23599. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23600. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23601. var particleSystem = this._particleSystems.data[particleIndex];
  23602. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23603. continue;
  23604. }
  23605. var emitter = particleSystem.emitter;
  23606. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23607. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23608. }
  23609. }
  23610. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23611. };
  23612. RenderingGroup.prototype._renderSprites = function () {
  23613. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23614. return;
  23615. }
  23616. // Sprites
  23617. var activeCamera = this._scene.activeCamera;
  23618. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23619. for (var id = 0; id < this._spriteManagers.length; id++) {
  23620. var spriteManager = this._spriteManagers.data[id];
  23621. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23622. spriteManager.render();
  23623. }
  23624. }
  23625. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23626. };
  23627. return RenderingGroup;
  23628. }());
  23629. BABYLON.RenderingGroup = RenderingGroup;
  23630. })(BABYLON || (BABYLON = {}));
  23631. //# sourceMappingURL=babylon.renderingGroup.js.map
  23632. var BABYLON;
  23633. (function (BABYLON) {
  23634. /**
  23635. * Groups all the scene component constants in one place to ease maintenance.
  23636. * @hidden
  23637. */
  23638. var SceneComponentConstants = /** @class */ (function () {
  23639. function SceneComponentConstants() {
  23640. }
  23641. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23642. SceneComponentConstants.NAME_LAYER = "Layer";
  23643. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23644. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23645. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23646. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23647. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  23648. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  23649. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  23650. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  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_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23659. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  23660. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  23661. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23662. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23663. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23664. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23665. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23666. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 0;
  23667. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 1;
  23668. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 2;
  23669. SceneComponentConstants.STEP_REBUILDGEOMETRY_POSTPROCESSRENDERPIPELINEMANAGER = 0;
  23670. return SceneComponentConstants;
  23671. }());
  23672. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23673. /**
  23674. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23675. * @hidden
  23676. */
  23677. var Stage = /** @class */ (function (_super) {
  23678. __extends(Stage, _super);
  23679. /**
  23680. * Hide ctor from the rest of the world.
  23681. * @param items The items to add.
  23682. */
  23683. function Stage(items) {
  23684. return _super.apply(this, items) || this;
  23685. }
  23686. /**
  23687. * Creates a new Stage.
  23688. * @returns A new instance of a Stage
  23689. */
  23690. Stage.Create = function () {
  23691. return Object.create(Stage.prototype);
  23692. };
  23693. /**
  23694. * Registers a step in an ordered way in the targeted stage.
  23695. * @param index Defines the position to register the step in
  23696. * @param component Defines the component attached to the step
  23697. * @param action Defines the action to launch during the step
  23698. */
  23699. Stage.prototype.registerStep = function (index, component, action) {
  23700. var i = 0;
  23701. var maxIndex = Number.MAX_VALUE;
  23702. for (; i < this.length && i < maxIndex; i++) {
  23703. var step = this[i];
  23704. maxIndex = step.index;
  23705. }
  23706. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23707. };
  23708. /**
  23709. * Clears all the steps from the stage.
  23710. */
  23711. Stage.prototype.clear = function () {
  23712. this.length = 0;
  23713. };
  23714. return Stage;
  23715. }(Array));
  23716. BABYLON.Stage = Stage;
  23717. })(BABYLON || (BABYLON = {}));
  23718. //# sourceMappingURL=babylon.sceneComponent.js.map
  23719. var BABYLON;
  23720. (function (BABYLON) {
  23721. /**
  23722. * Base class of the scene acting as a container for the different elements composing a scene.
  23723. * This class is dynamically extended by the different components of the scene increasing
  23724. * flexibility and reducing coupling
  23725. */
  23726. var AbstractScene = /** @class */ (function () {
  23727. function AbstractScene() {
  23728. /** All of the cameras added to this scene
  23729. * @see http://doc.babylonjs.com/babylon101/cameras
  23730. */
  23731. this.cameras = new Array();
  23732. /**
  23733. * All of the lights added to this scene
  23734. * @see http://doc.babylonjs.com/babylon101/lights
  23735. */
  23736. this.lights = new Array();
  23737. /**
  23738. * All of the (abstract) meshes added to this scene
  23739. */
  23740. this.meshes = new Array();
  23741. /**
  23742. * The list of skeletons added to the scene
  23743. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23744. */
  23745. this.skeletons = new Array();
  23746. /**
  23747. * All of the particle systems added to this scene
  23748. * @see http://doc.babylonjs.com/babylon101/particles
  23749. */
  23750. this.particleSystems = new Array();
  23751. /**
  23752. * Gets a list of Animations associated with the scene
  23753. */
  23754. this.animations = [];
  23755. /**
  23756. * All of the animation groups added to this scene
  23757. * @see http://doc.babylonjs.com/how_to/group
  23758. */
  23759. this.animationGroups = new Array();
  23760. /**
  23761. * All of the multi-materials added to this scene
  23762. * @see http://doc.babylonjs.com/how_to/multi_materials
  23763. */
  23764. this.multiMaterials = new Array();
  23765. /**
  23766. * All of the materials added to this scene
  23767. * @see http://doc.babylonjs.com/babylon101/materials
  23768. */
  23769. this.materials = new Array();
  23770. /**
  23771. * The list of morph target managers added to the scene
  23772. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23773. */
  23774. this.morphTargetManagers = new Array();
  23775. /**
  23776. * The list of geometries used in the scene.
  23777. */
  23778. this.geometries = new Array();
  23779. /**
  23780. * All of the tranform nodes added to this scene
  23781. * @see http://doc.babylonjs.com/how_to/transformnode
  23782. */
  23783. this.transformNodes = new Array();
  23784. /**
  23785. * ActionManagers available on the scene.
  23786. */
  23787. this.actionManagers = new Array();
  23788. /**
  23789. * Sounds to keep.
  23790. */
  23791. this.sounds = new Array();
  23792. /**
  23793. * Textures to keep.
  23794. */
  23795. this.textures = new Array();
  23796. }
  23797. /**
  23798. * Adds a parser in the list of available ones
  23799. * @param name Defines the name of the parser
  23800. * @param parser Defines the parser to add
  23801. */
  23802. AbstractScene.AddParser = function (name, parser) {
  23803. this._BabylonFileParsers[name] = parser;
  23804. };
  23805. /**
  23806. * Gets a general parser from the list of avaialble ones
  23807. * @param name Defines the name of the parser
  23808. * @returns the requested parser or null
  23809. */
  23810. AbstractScene.GetParser = function (name) {
  23811. if (this._BabylonFileParsers[name]) {
  23812. return this._BabylonFileParsers[name];
  23813. }
  23814. return null;
  23815. };
  23816. /**
  23817. * Adds n individual parser in the list of available ones
  23818. * @param name Defines the name of the parser
  23819. * @param parser Defines the parser to add
  23820. */
  23821. AbstractScene.AddIndividualParser = function (name, parser) {
  23822. this._IndividualBabylonFileParsers[name] = parser;
  23823. };
  23824. /**
  23825. * Gets an individual parser from the list of avaialble ones
  23826. * @param name Defines the name of the parser
  23827. * @returns the requested parser or null
  23828. */
  23829. AbstractScene.GetIndividualParser = function (name) {
  23830. if (this._IndividualBabylonFileParsers[name]) {
  23831. return this._IndividualBabylonFileParsers[name];
  23832. }
  23833. return null;
  23834. };
  23835. /**
  23836. * Parser json data and populate both a scene and its associated container object
  23837. * @param jsonData Defines the data to parse
  23838. * @param scene Defines the scene to parse the data for
  23839. * @param container Defines the container attached to the parsing sequence
  23840. * @param rootUrl Defines the root url of the data
  23841. */
  23842. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23843. for (var parserName in this._BabylonFileParsers) {
  23844. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23845. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23846. }
  23847. }
  23848. };
  23849. /**
  23850. * Stores the list of available parsers in the application.
  23851. */
  23852. AbstractScene._BabylonFileParsers = {};
  23853. /**
  23854. * Stores the list of available individual parsers in the application.
  23855. */
  23856. AbstractScene._IndividualBabylonFileParsers = {};
  23857. return AbstractScene;
  23858. }());
  23859. BABYLON.AbstractScene = AbstractScene;
  23860. })(BABYLON || (BABYLON = {}));
  23861. //# sourceMappingURL=babylon.abstractScene.js.map
  23862. var BABYLON;
  23863. (function (BABYLON) {
  23864. /** @hidden */
  23865. var ClickInfo = /** @class */ (function () {
  23866. function ClickInfo() {
  23867. this._singleClick = false;
  23868. this._doubleClick = false;
  23869. this._hasSwiped = false;
  23870. this._ignore = false;
  23871. }
  23872. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23873. get: function () {
  23874. return this._singleClick;
  23875. },
  23876. set: function (b) {
  23877. this._singleClick = b;
  23878. },
  23879. enumerable: true,
  23880. configurable: true
  23881. });
  23882. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23883. get: function () {
  23884. return this._doubleClick;
  23885. },
  23886. set: function (b) {
  23887. this._doubleClick = b;
  23888. },
  23889. enumerable: true,
  23890. configurable: true
  23891. });
  23892. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23893. get: function () {
  23894. return this._hasSwiped;
  23895. },
  23896. set: function (b) {
  23897. this._hasSwiped = b;
  23898. },
  23899. enumerable: true,
  23900. configurable: true
  23901. });
  23902. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23903. get: function () {
  23904. return this._ignore;
  23905. },
  23906. set: function (b) {
  23907. this._ignore = b;
  23908. },
  23909. enumerable: true,
  23910. configurable: true
  23911. });
  23912. return ClickInfo;
  23913. }());
  23914. /**
  23915. * This class is used by the onRenderingGroupObservable
  23916. */
  23917. var RenderingGroupInfo = /** @class */ (function () {
  23918. function RenderingGroupInfo() {
  23919. }
  23920. return RenderingGroupInfo;
  23921. }());
  23922. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23923. /**
  23924. * Represents a scene to be rendered by the engine.
  23925. * @see http://doc.babylonjs.com/features/scene
  23926. */
  23927. var Scene = /** @class */ (function (_super) {
  23928. __extends(Scene, _super);
  23929. /**
  23930. * Creates a new Scene
  23931. * @param engine defines the engine to use to render this scene
  23932. */
  23933. function Scene(engine) {
  23934. var _this = _super.call(this) || this;
  23935. // Members
  23936. /**
  23937. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23938. */
  23939. _this.autoClear = true;
  23940. /**
  23941. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23942. */
  23943. _this.autoClearDepthAndStencil = true;
  23944. /**
  23945. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23946. */
  23947. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23948. /**
  23949. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23950. */
  23951. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23952. _this._forceWireframe = false;
  23953. _this._forcePointsCloud = false;
  23954. /**
  23955. * Gets or sets a boolean indicating if animations are enabled
  23956. */
  23957. _this.animationsEnabled = true;
  23958. _this._animationPropertiesOverride = null;
  23959. /**
  23960. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23961. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23962. */
  23963. _this.useConstantAnimationDeltaTime = false;
  23964. /**
  23965. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23966. * Please note that it requires to run a ray cast through the scene on every frame
  23967. */
  23968. _this.constantlyUpdateMeshUnderPointer = false;
  23969. /**
  23970. * Defines the HTML cursor to use when hovering over interactive elements
  23971. */
  23972. _this.hoverCursor = "pointer";
  23973. /**
  23974. * Defines the HTML default cursor to use (empty by default)
  23975. */
  23976. _this.defaultCursor = "";
  23977. /**
  23978. * This is used to call preventDefault() on pointer down
  23979. * in order to block unwanted artifacts like system double clicks
  23980. */
  23981. _this.preventDefaultOnPointerDown = true;
  23982. // Metadata
  23983. /**
  23984. * Gets or sets user defined metadata
  23985. */
  23986. _this.metadata = null;
  23987. /**
  23988. * Use this array to add regular expressions used to disable offline support for specific urls
  23989. */
  23990. _this.disableOfflineSupportExceptionRules = new Array();
  23991. /**
  23992. * An event triggered when the scene is disposed.
  23993. */
  23994. _this.onDisposeObservable = new BABYLON.Observable();
  23995. _this._onDisposeObserver = null;
  23996. /**
  23997. * An event triggered before rendering the scene (right after animations and physics)
  23998. */
  23999. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24000. _this._onBeforeRenderObserver = null;
  24001. /**
  24002. * An event triggered after rendering the scene
  24003. */
  24004. _this.onAfterRenderObservable = new BABYLON.Observable();
  24005. _this._onAfterRenderObserver = null;
  24006. /**
  24007. * An event triggered before animating the scene
  24008. */
  24009. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24010. /**
  24011. * An event triggered after animations processing
  24012. */
  24013. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24014. /**
  24015. * An event triggered before draw calls are ready to be sent
  24016. */
  24017. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24018. /**
  24019. * An event triggered after draw calls have been sent
  24020. */
  24021. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24022. /**
  24023. * An event triggered when physic simulation is about to be run
  24024. */
  24025. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  24026. /**
  24027. * An event triggered when physic simulation has been done
  24028. */
  24029. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  24030. /**
  24031. * An event triggered when the scene is ready
  24032. */
  24033. _this.onReadyObservable = new BABYLON.Observable();
  24034. /**
  24035. * An event triggered before rendering a camera
  24036. */
  24037. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24038. _this._onBeforeCameraRenderObserver = null;
  24039. /**
  24040. * An event triggered after rendering a camera
  24041. */
  24042. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24043. _this._onAfterCameraRenderObserver = null;
  24044. /**
  24045. * An event triggered when active meshes evaluation is about to start
  24046. */
  24047. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24048. /**
  24049. * An event triggered when active meshes evaluation is done
  24050. */
  24051. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24052. /**
  24053. * An event triggered when particles rendering is about to start
  24054. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24055. */
  24056. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24057. /**
  24058. * An event triggered when particles rendering is done
  24059. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24060. */
  24061. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24062. /**
  24063. * An event triggered when sprites rendering is about to start
  24064. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24065. */
  24066. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  24067. /**
  24068. * An event triggered when sprites rendering is done
  24069. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24070. */
  24071. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  24072. /**
  24073. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24074. */
  24075. _this.onDataLoadedObservable = new BABYLON.Observable();
  24076. /**
  24077. * An event triggered when a camera is created
  24078. */
  24079. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24080. /**
  24081. * An event triggered when a camera is removed
  24082. */
  24083. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24084. /**
  24085. * An event triggered when a light is created
  24086. */
  24087. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24088. /**
  24089. * An event triggered when a light is removed
  24090. */
  24091. _this.onLightRemovedObservable = new BABYLON.Observable();
  24092. /**
  24093. * An event triggered when a geometry is created
  24094. */
  24095. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24096. /**
  24097. * An event triggered when a geometry is removed
  24098. */
  24099. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24100. /**
  24101. * An event triggered when a transform node is created
  24102. */
  24103. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24104. /**
  24105. * An event triggered when a transform node is removed
  24106. */
  24107. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24108. /**
  24109. * An event triggered when a mesh is created
  24110. */
  24111. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24112. /**
  24113. * An event triggered when a mesh is removed
  24114. */
  24115. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24116. /**
  24117. * An event triggered when render targets are about to be rendered
  24118. * Can happen multiple times per frame.
  24119. */
  24120. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24121. /**
  24122. * An event triggered when render targets were rendered.
  24123. * Can happen multiple times per frame.
  24124. */
  24125. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24126. /**
  24127. * An event triggered before calculating deterministic simulation step
  24128. */
  24129. _this.onBeforeStepObservable = new BABYLON.Observable();
  24130. /**
  24131. * An event triggered after calculating deterministic simulation step
  24132. */
  24133. _this.onAfterStepObservable = new BABYLON.Observable();
  24134. /**
  24135. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24136. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24137. * 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)
  24138. */
  24139. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24140. /**
  24141. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24142. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24143. * 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)
  24144. */
  24145. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24146. // Animations
  24147. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24148. /**
  24149. * 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).
  24150. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24151. */
  24152. _this.onPrePointerObservable = new BABYLON.Observable();
  24153. /**
  24154. * Observable event triggered each time an input event is received from the rendering canvas
  24155. */
  24156. _this.onPointerObservable = new BABYLON.Observable();
  24157. _this._meshPickProceed = false;
  24158. _this._currentPickResult = null;
  24159. _this._previousPickResult = null;
  24160. _this._totalPointersPressed = 0;
  24161. _this._doubleClickOccured = false;
  24162. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24163. _this.cameraToUseForPointers = null;
  24164. _this._pointerX = 0;
  24165. _this._pointerY = 0;
  24166. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24167. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24168. _this._startingPointerTime = 0;
  24169. _this._previousStartingPointerTime = 0;
  24170. _this._pointerCaptures = {};
  24171. // Deterministic lockstep
  24172. _this._timeAccumulator = 0;
  24173. _this._currentStepId = 0;
  24174. _this._currentInternalStep = 0;
  24175. // Keyboard
  24176. /**
  24177. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24178. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24179. */
  24180. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24181. /**
  24182. * Observable event triggered each time an keyboard event is received from the hosting window
  24183. */
  24184. _this.onKeyboardObservable = new BABYLON.Observable();
  24185. // Coordinates system
  24186. _this._useRightHandedSystem = false;
  24187. // Fog
  24188. _this._fogEnabled = true;
  24189. _this._fogMode = Scene.FOGMODE_NONE;
  24190. /**
  24191. * Gets or sets the fog color to use
  24192. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24193. */
  24194. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24195. /**
  24196. * Gets or sets the fog density to use
  24197. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24198. */
  24199. _this.fogDensity = 0.1;
  24200. /**
  24201. * Gets or sets the fog start distance to use
  24202. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24203. */
  24204. _this.fogStart = 0;
  24205. /**
  24206. * Gets or sets the fog end distance to use
  24207. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24208. */
  24209. _this.fogEnd = 1000.0;
  24210. // Lights
  24211. _this._shadowsEnabled = true;
  24212. _this._lightsEnabled = true;
  24213. /** All of the active cameras added to this scene. */
  24214. _this.activeCameras = new Array();
  24215. // Textures
  24216. _this._texturesEnabled = true;
  24217. // Particles
  24218. /**
  24219. * Gets or sets a boolean indicating if particles are enabled on this scene
  24220. */
  24221. _this.particlesEnabled = true;
  24222. // Sprites
  24223. /**
  24224. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24225. */
  24226. _this.spritesEnabled = true;
  24227. /**
  24228. * All of the sprite managers added to this scene
  24229. * @see http://doc.babylonjs.com/babylon101/sprites
  24230. */
  24231. _this.spriteManagers = new Array();
  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. /**
  24283. * The list of reflection probes added to the scene
  24284. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24285. */
  24286. _this.reflectionProbes = new Array();
  24287. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24288. // Procedural textures
  24289. /**
  24290. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24291. */
  24292. _this.proceduralTexturesEnabled = true;
  24293. /**
  24294. * The list of procedural textures added to the scene
  24295. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24296. */
  24297. _this.proceduralTextures = new Array();
  24298. /**
  24299. * The list of sound tracks added to the scene
  24300. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24301. */
  24302. _this.soundTracks = new Array();
  24303. _this._audioEnabled = true;
  24304. _this._headphone = false;
  24305. // Performance counters
  24306. _this._totalVertices = new BABYLON.PerfCounter();
  24307. /** @hidden */
  24308. _this._activeIndices = new BABYLON.PerfCounter();
  24309. /** @hidden */
  24310. _this._activeParticles = new BABYLON.PerfCounter();
  24311. /** @hidden */
  24312. _this._activeBones = new BABYLON.PerfCounter();
  24313. _this._animationTime = 0;
  24314. /**
  24315. * Gets or sets a general scale for animation speed
  24316. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24317. */
  24318. _this.animationTimeScale = 1;
  24319. _this._renderId = 0;
  24320. _this._executeWhenReadyTimeoutId = -1;
  24321. _this._intermediateRendering = false;
  24322. _this._viewUpdateFlag = -1;
  24323. _this._projectionUpdateFlag = -1;
  24324. _this._alternateViewUpdateFlag = -1;
  24325. _this._alternateProjectionUpdateFlag = -1;
  24326. /** @hidden */
  24327. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24328. _this._activeRequests = new Array();
  24329. _this._pendingData = new Array();
  24330. _this._isDisposed = false;
  24331. /**
  24332. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24333. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24334. */
  24335. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24336. _this._activeMeshes = new BABYLON.SmartArray(256);
  24337. _this._processedMaterials = new BABYLON.SmartArray(256);
  24338. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24339. /** @hidden */
  24340. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24341. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24342. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24343. /** @hidden */
  24344. _this._activeAnimatables = new Array();
  24345. _this._transformMatrix = BABYLON.Matrix.Zero();
  24346. _this._useAlternateCameraConfiguration = false;
  24347. _this._alternateRendering = false;
  24348. /**
  24349. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24350. * This is useful if there are more lights that the maximum simulteanous authorized
  24351. */
  24352. _this.requireLightSorting = false;
  24353. /**
  24354. * @hidden
  24355. * Backing store of defined scene components.
  24356. */
  24357. _this._components = [];
  24358. /**
  24359. * @hidden
  24360. * Backing store of defined scene components.
  24361. */
  24362. _this._serializableComponents = [];
  24363. /**
  24364. * List of components to register on the next registration step.
  24365. */
  24366. _this._transientComponents = [];
  24367. /**
  24368. * @hidden
  24369. * Defines the actions happening before camera updates.
  24370. */
  24371. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24372. /**
  24373. * @hidden
  24374. * Defines the actions happening before camera updates.
  24375. */
  24376. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24377. /**
  24378. * @hidden
  24379. * Defines the actions happening during the per mesh ready checks.
  24380. */
  24381. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24382. /**
  24383. * @hidden
  24384. * Defines the actions happening before evaluate active mesh checks.
  24385. */
  24386. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24387. /**
  24388. * @hidden
  24389. * Defines the actions happening during the evaluate sub mesh checks.
  24390. */
  24391. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24392. /**
  24393. * @hidden
  24394. * Defines the actions happening during the active mesh stage.
  24395. */
  24396. _this._activeMeshStage = BABYLON.Stage.Create();
  24397. /**
  24398. * @hidden
  24399. * Defines the actions happening during the per camera render target step.
  24400. */
  24401. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24402. /**
  24403. * @hidden
  24404. * Defines the actions happening just before the active camera is drawing.
  24405. */
  24406. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24407. /**
  24408. * Defines the actions happening just before a rendering group is drawing.
  24409. */
  24410. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24411. /**
  24412. * @hidden
  24413. * Defines the actions happening just after a rendering group has been drawn.
  24414. */
  24415. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24416. /**
  24417. * @hidden
  24418. * Defines the actions happening just after the active camera has been drawn.
  24419. */
  24420. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24421. /**
  24422. * @hidden
  24423. * Defines the actions happening when Geometries are rebuilding.
  24424. */
  24425. _this._rebuildGeometryStage = BABYLON.Stage.Create();
  24426. _this._activeMeshesFrozen = false;
  24427. /** @hidden */
  24428. _this._allowPostProcessClear = true;
  24429. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24430. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  24431. _this.blockMaterialDirtyMechanism = false;
  24432. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24433. _this._engine.scenes.push(_this);
  24434. _this._uid = null;
  24435. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24436. if (BABYLON.PostProcessManager) {
  24437. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24438. }
  24439. if (BABYLON.OutlineRenderer) {
  24440. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24441. }
  24442. if (BABYLON.Tools.IsWindowObjectExist()) {
  24443. _this.attachControl();
  24444. }
  24445. //collision coordinator initialization. For now legacy per default.
  24446. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24447. // Uniform Buffer
  24448. _this._createUbo();
  24449. // Default Image processing definition
  24450. if (BABYLON.ImageProcessingConfiguration) {
  24451. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24452. }
  24453. return _this;
  24454. }
  24455. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24456. /**
  24457. * Texture used in all pbr material as the reflection texture.
  24458. * As in the majority of the scene they are the same (exception for multi room and so on),
  24459. * this is easier to reference from here than from all the materials.
  24460. */
  24461. get: function () {
  24462. return this._environmentTexture;
  24463. },
  24464. /**
  24465. * Texture used in all pbr material as the reflection texture.
  24466. * As in the majority of the scene they are the same (exception for multi room and so on),
  24467. * this is easier to set here than in all the materials.
  24468. */
  24469. set: function (value) {
  24470. if (this._environmentTexture === value) {
  24471. return;
  24472. }
  24473. this._environmentTexture = value;
  24474. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24475. },
  24476. enumerable: true,
  24477. configurable: true
  24478. });
  24479. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24480. /**
  24481. * Default image processing configuration used either in the rendering
  24482. * Forward main pass or through the imageProcessingPostProcess if present.
  24483. * As in the majority of the scene they are the same (exception for multi camera),
  24484. * this is easier to reference from here than from all the materials and post process.
  24485. *
  24486. * No setter as we it is a shared configuration, you can set the values instead.
  24487. */
  24488. get: function () {
  24489. return this._imageProcessingConfiguration;
  24490. },
  24491. enumerable: true,
  24492. configurable: true
  24493. });
  24494. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24495. get: function () {
  24496. return this._forceWireframe;
  24497. },
  24498. /**
  24499. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24500. */
  24501. set: function (value) {
  24502. if (this._forceWireframe === value) {
  24503. return;
  24504. }
  24505. this._forceWireframe = value;
  24506. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24507. },
  24508. enumerable: true,
  24509. configurable: true
  24510. });
  24511. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24512. get: function () {
  24513. return this._forcePointsCloud;
  24514. },
  24515. /**
  24516. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24517. */
  24518. set: function (value) {
  24519. if (this._forcePointsCloud === value) {
  24520. return;
  24521. }
  24522. this._forcePointsCloud = value;
  24523. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24524. },
  24525. enumerable: true,
  24526. configurable: true
  24527. });
  24528. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24529. /**
  24530. * Gets or sets the animation properties override
  24531. */
  24532. get: function () {
  24533. return this._animationPropertiesOverride;
  24534. },
  24535. set: function (value) {
  24536. this._animationPropertiesOverride = value;
  24537. },
  24538. enumerable: true,
  24539. configurable: true
  24540. });
  24541. Object.defineProperty(Scene.prototype, "onDispose", {
  24542. /** Sets a function to be executed when this scene is disposed. */
  24543. set: function (callback) {
  24544. if (this._onDisposeObserver) {
  24545. this.onDisposeObservable.remove(this._onDisposeObserver);
  24546. }
  24547. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24548. },
  24549. enumerable: true,
  24550. configurable: true
  24551. });
  24552. Object.defineProperty(Scene.prototype, "beforeRender", {
  24553. /** Sets a function to be executed before rendering this scene */
  24554. set: function (callback) {
  24555. if (this._onBeforeRenderObserver) {
  24556. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24557. }
  24558. if (callback) {
  24559. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24560. }
  24561. },
  24562. enumerable: true,
  24563. configurable: true
  24564. });
  24565. Object.defineProperty(Scene.prototype, "afterRender", {
  24566. /** Sets a function to be executed after rendering this scene */
  24567. set: function (callback) {
  24568. if (this._onAfterRenderObserver) {
  24569. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24570. }
  24571. if (callback) {
  24572. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24573. }
  24574. },
  24575. enumerable: true,
  24576. configurable: true
  24577. });
  24578. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24579. /** Sets a function to be executed before rendering a camera*/
  24580. set: function (callback) {
  24581. if (this._onBeforeCameraRenderObserver) {
  24582. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24583. }
  24584. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24585. },
  24586. enumerable: true,
  24587. configurable: true
  24588. });
  24589. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24590. /** Sets a function to be executed after rendering a camera*/
  24591. set: function (callback) {
  24592. if (this._onAfterCameraRenderObserver) {
  24593. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24594. }
  24595. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24596. },
  24597. enumerable: true,
  24598. configurable: true
  24599. });
  24600. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24601. /**
  24602. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24603. */
  24604. get: function () {
  24605. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24606. },
  24607. enumerable: true,
  24608. configurable: true
  24609. });
  24610. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24611. get: function () {
  24612. return this._useRightHandedSystem;
  24613. },
  24614. /**
  24615. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24616. */
  24617. set: function (value) {
  24618. if (this._useRightHandedSystem === value) {
  24619. return;
  24620. }
  24621. this._useRightHandedSystem = value;
  24622. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24623. },
  24624. enumerable: true,
  24625. configurable: true
  24626. });
  24627. /**
  24628. * Sets the step Id used by deterministic lock step
  24629. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24630. * @param newStepId defines the step Id
  24631. */
  24632. Scene.prototype.setStepId = function (newStepId) {
  24633. this._currentStepId = newStepId;
  24634. };
  24635. ;
  24636. /**
  24637. * Gets the step Id used by deterministic lock step
  24638. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24639. * @returns the step Id
  24640. */
  24641. Scene.prototype.getStepId = function () {
  24642. return this._currentStepId;
  24643. };
  24644. ;
  24645. /**
  24646. * Gets the internal step used by deterministic lock step
  24647. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24648. * @returns the internal step
  24649. */
  24650. Scene.prototype.getInternalStep = function () {
  24651. return this._currentInternalStep;
  24652. };
  24653. ;
  24654. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24655. get: function () {
  24656. return this._fogEnabled;
  24657. },
  24658. /**
  24659. * Gets or sets a boolean indicating if fog is enabled on this scene
  24660. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24661. */
  24662. set: function (value) {
  24663. if (this._fogEnabled === value) {
  24664. return;
  24665. }
  24666. this._fogEnabled = value;
  24667. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24668. },
  24669. enumerable: true,
  24670. configurable: true
  24671. });
  24672. Object.defineProperty(Scene.prototype, "fogMode", {
  24673. get: function () {
  24674. return this._fogMode;
  24675. },
  24676. /**
  24677. * Gets or sets the fog mode to use
  24678. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24679. */
  24680. set: function (value) {
  24681. if (this._fogMode === value) {
  24682. return;
  24683. }
  24684. this._fogMode = value;
  24685. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24686. },
  24687. enumerable: true,
  24688. configurable: true
  24689. });
  24690. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24691. get: function () {
  24692. return this._shadowsEnabled;
  24693. },
  24694. /**
  24695. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24696. */
  24697. set: function (value) {
  24698. if (this._shadowsEnabled === value) {
  24699. return;
  24700. }
  24701. this._shadowsEnabled = value;
  24702. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24703. },
  24704. enumerable: true,
  24705. configurable: true
  24706. });
  24707. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24708. get: function () {
  24709. return this._lightsEnabled;
  24710. },
  24711. /**
  24712. * Gets or sets a boolean indicating if lights are enabled on this scene
  24713. */
  24714. set: function (value) {
  24715. if (this._lightsEnabled === value) {
  24716. return;
  24717. }
  24718. this._lightsEnabled = value;
  24719. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24720. },
  24721. enumerable: true,
  24722. configurable: true
  24723. });
  24724. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24725. /** The default material used on meshes when no material is affected */
  24726. get: function () {
  24727. if (!this._defaultMaterial) {
  24728. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24729. }
  24730. return this._defaultMaterial;
  24731. },
  24732. /** The default material used on meshes when no material is affected */
  24733. set: function (value) {
  24734. this._defaultMaterial = value;
  24735. },
  24736. enumerable: true,
  24737. configurable: true
  24738. });
  24739. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24740. get: function () {
  24741. return this._texturesEnabled;
  24742. },
  24743. /**
  24744. * Gets or sets a boolean indicating if textures are enabled on this scene
  24745. */
  24746. set: function (value) {
  24747. if (this._texturesEnabled === value) {
  24748. return;
  24749. }
  24750. this._texturesEnabled = value;
  24751. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24752. },
  24753. enumerable: true,
  24754. configurable: true
  24755. });
  24756. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24757. get: function () {
  24758. return this._skeletonsEnabled;
  24759. },
  24760. /**
  24761. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24762. */
  24763. set: function (value) {
  24764. if (this._skeletonsEnabled === value) {
  24765. return;
  24766. }
  24767. this._skeletonsEnabled = value;
  24768. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24769. },
  24770. enumerable: true,
  24771. configurable: true
  24772. });
  24773. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24774. /**
  24775. * Gets the main soundtrack associated with the scene
  24776. */
  24777. get: function () {
  24778. if (!this._mainSoundTrack) {
  24779. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24780. }
  24781. return this._mainSoundTrack;
  24782. },
  24783. enumerable: true,
  24784. configurable: true
  24785. });
  24786. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24787. /** @hidden */
  24788. get: function () {
  24789. return this._alternateRendering;
  24790. },
  24791. enumerable: true,
  24792. configurable: true
  24793. });
  24794. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24795. /**
  24796. * Gets the list of frustum planes (built from the active camera)
  24797. */
  24798. get: function () {
  24799. return this._frustumPlanes;
  24800. },
  24801. enumerable: true,
  24802. configurable: true
  24803. });
  24804. /**
  24805. * Registers the transient components if needed.
  24806. */
  24807. Scene.prototype._registerTransientComponents = function () {
  24808. // Register components that have been associated lately to the scene.
  24809. if (this._transientComponents.length > 0) {
  24810. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24811. var component = _a[_i];
  24812. component.register();
  24813. }
  24814. this._transientComponents = [];
  24815. }
  24816. };
  24817. /**
  24818. * @hidden
  24819. * Add a component to the scene.
  24820. * Note that the ccomponent could be registered on th next frame if this is called after
  24821. * the register component stage.
  24822. * @param component Defines the component to add to the scene
  24823. */
  24824. Scene.prototype._addComponent = function (component) {
  24825. this._components.push(component);
  24826. this._transientComponents.push(component);
  24827. var serializableComponent = component;
  24828. if (serializableComponent.addFromContainer) {
  24829. this._serializableComponents.push(serializableComponent);
  24830. }
  24831. };
  24832. /**
  24833. * @hidden
  24834. * Gets a component from the scene.
  24835. * @param name defines the name of the component to retrieve
  24836. * @returns the component or null if not present
  24837. */
  24838. Scene.prototype._getComponent = function (name) {
  24839. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24840. var component = _a[_i];
  24841. if (component.name === name) {
  24842. return component;
  24843. }
  24844. }
  24845. return null;
  24846. };
  24847. Object.defineProperty(Scene.prototype, "debugLayer", {
  24848. /**
  24849. * Gets the debug layer (aka Inspector) associated with the scene
  24850. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24851. */
  24852. get: function () {
  24853. if (!this._debugLayer) {
  24854. this._debugLayer = new BABYLON.DebugLayer(this);
  24855. }
  24856. return this._debugLayer;
  24857. },
  24858. enumerable: true,
  24859. configurable: true
  24860. });
  24861. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24862. /**
  24863. * Gets a boolean indicating if collisions are processed on a web worker
  24864. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24865. */
  24866. get: function () {
  24867. return this._workerCollisions;
  24868. },
  24869. set: function (enabled) {
  24870. if (!BABYLON.CollisionCoordinatorLegacy) {
  24871. return;
  24872. }
  24873. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24874. this._workerCollisions = enabled;
  24875. if (this.collisionCoordinator) {
  24876. this.collisionCoordinator.destroy();
  24877. }
  24878. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24879. this.collisionCoordinator.init(this);
  24880. },
  24881. enumerable: true,
  24882. configurable: true
  24883. });
  24884. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24885. /**
  24886. * Gets the octree used to boost mesh selection (picking)
  24887. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24888. */
  24889. get: function () {
  24890. return this._selectionOctree;
  24891. },
  24892. enumerable: true,
  24893. configurable: true
  24894. });
  24895. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24896. /**
  24897. * Gets the mesh that is currently under the pointer
  24898. */
  24899. get: function () {
  24900. return this._pointerOverMesh;
  24901. },
  24902. enumerable: true,
  24903. configurable: true
  24904. });
  24905. Object.defineProperty(Scene.prototype, "pointerX", {
  24906. /**
  24907. * Gets the current on-screen X position of the pointer
  24908. */
  24909. get: function () {
  24910. return this._pointerX;
  24911. },
  24912. enumerable: true,
  24913. configurable: true
  24914. });
  24915. Object.defineProperty(Scene.prototype, "pointerY", {
  24916. /**
  24917. * Gets the current on-screen Y position of the pointer
  24918. */
  24919. get: function () {
  24920. return this._pointerY;
  24921. },
  24922. enumerable: true,
  24923. configurable: true
  24924. });
  24925. /**
  24926. * Gets the cached material (ie. the latest rendered one)
  24927. * @returns the cached material
  24928. */
  24929. Scene.prototype.getCachedMaterial = function () {
  24930. return this._cachedMaterial;
  24931. };
  24932. /**
  24933. * Gets the cached effect (ie. the latest rendered one)
  24934. * @returns the cached effect
  24935. */
  24936. Scene.prototype.getCachedEffect = function () {
  24937. return this._cachedEffect;
  24938. };
  24939. /**
  24940. * Gets the cached visibility state (ie. the latest rendered one)
  24941. * @returns the cached visibility state
  24942. */
  24943. Scene.prototype.getCachedVisibility = function () {
  24944. return this._cachedVisibility;
  24945. };
  24946. /**
  24947. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24948. * @param material defines the current material
  24949. * @param effect defines the current effect
  24950. * @param visibility defines the current visibility state
  24951. * @returns true if one parameter is not cached
  24952. */
  24953. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24954. if (visibility === void 0) { visibility = 1; }
  24955. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24956. };
  24957. /**
  24958. * Gets the outline renderer associated with the scene
  24959. * @returns a OutlineRenderer
  24960. */
  24961. Scene.prototype.getOutlineRenderer = function () {
  24962. return this._outlineRenderer;
  24963. };
  24964. /**
  24965. * Gets the engine associated with the scene
  24966. * @returns an Engine
  24967. */
  24968. Scene.prototype.getEngine = function () {
  24969. return this._engine;
  24970. };
  24971. /**
  24972. * Gets the total number of vertices rendered per frame
  24973. * @returns the total number of vertices rendered per frame
  24974. */
  24975. Scene.prototype.getTotalVertices = function () {
  24976. return this._totalVertices.current;
  24977. };
  24978. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24979. /**
  24980. * Gets the performance counter for total vertices
  24981. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24982. */
  24983. get: function () {
  24984. return this._totalVertices;
  24985. },
  24986. enumerable: true,
  24987. configurable: true
  24988. });
  24989. /**
  24990. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24991. * @returns the total number of active indices rendered per frame
  24992. */
  24993. Scene.prototype.getActiveIndices = function () {
  24994. return this._activeIndices.current;
  24995. };
  24996. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24997. /**
  24998. * Gets the performance counter for active indices
  24999. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25000. */
  25001. get: function () {
  25002. return this._activeIndices;
  25003. },
  25004. enumerable: true,
  25005. configurable: true
  25006. });
  25007. /**
  25008. * Gets the total number of active particles rendered per frame
  25009. * @returns the total number of active particles rendered per frame
  25010. */
  25011. Scene.prototype.getActiveParticles = function () {
  25012. return this._activeParticles.current;
  25013. };
  25014. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25015. /**
  25016. * Gets the performance counter for active particles
  25017. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25018. */
  25019. get: function () {
  25020. return this._activeParticles;
  25021. },
  25022. enumerable: true,
  25023. configurable: true
  25024. });
  25025. /**
  25026. * Gets the total number of active bones rendered per frame
  25027. * @returns the total number of active bones rendered per frame
  25028. */
  25029. Scene.prototype.getActiveBones = function () {
  25030. return this._activeBones.current;
  25031. };
  25032. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25033. /**
  25034. * Gets the performance counter for active bones
  25035. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25036. */
  25037. get: function () {
  25038. return this._activeBones;
  25039. },
  25040. enumerable: true,
  25041. configurable: true
  25042. });
  25043. /** @hidden */
  25044. Scene.prototype.getInterFramePerfCounter = function () {
  25045. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25046. return 0;
  25047. };
  25048. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25049. /** @hidden */
  25050. get: function () {
  25051. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25052. return null;
  25053. },
  25054. enumerable: true,
  25055. configurable: true
  25056. });
  25057. /** @hidden */
  25058. Scene.prototype.getLastFrameDuration = function () {
  25059. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25060. return 0;
  25061. };
  25062. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25063. /** @hidden */
  25064. get: function () {
  25065. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25066. return null;
  25067. },
  25068. enumerable: true,
  25069. configurable: true
  25070. });
  25071. /** @hidden */
  25072. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25073. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25074. return 0;
  25075. };
  25076. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25077. /** @hidden */
  25078. get: function () {
  25079. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25080. return null;
  25081. },
  25082. enumerable: true,
  25083. configurable: true
  25084. });
  25085. /**
  25086. * Gets the array of active meshes
  25087. * @returns an array of AbstractMesh
  25088. */
  25089. Scene.prototype.getActiveMeshes = function () {
  25090. return this._activeMeshes;
  25091. };
  25092. /** @hidden */
  25093. Scene.prototype.getRenderTargetsDuration = function () {
  25094. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25095. return 0;
  25096. };
  25097. /** @hidden */
  25098. Scene.prototype.getRenderDuration = function () {
  25099. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25100. return 0;
  25101. };
  25102. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25103. /** @hidden */
  25104. get: function () {
  25105. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25106. return null;
  25107. },
  25108. enumerable: true,
  25109. configurable: true
  25110. });
  25111. /** @hidden */
  25112. Scene.prototype.getParticlesDuration = function () {
  25113. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25114. return 0;
  25115. };
  25116. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25117. /** @hidden */
  25118. get: function () {
  25119. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25120. return null;
  25121. },
  25122. enumerable: true,
  25123. configurable: true
  25124. });
  25125. /** @hidden */
  25126. Scene.prototype.getSpritesDuration = function () {
  25127. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25128. return 0;
  25129. };
  25130. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25131. /** @hidden */
  25132. get: function () {
  25133. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25134. return null;
  25135. },
  25136. enumerable: true,
  25137. configurable: true
  25138. });
  25139. /**
  25140. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25141. * @returns a number
  25142. */
  25143. Scene.prototype.getAnimationRatio = function () {
  25144. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25145. };
  25146. /**
  25147. * Gets an unique Id for the current frame
  25148. * @returns a number
  25149. */
  25150. Scene.prototype.getRenderId = function () {
  25151. return this._renderId;
  25152. };
  25153. /** Call this function if you want to manually increment the render Id*/
  25154. Scene.prototype.incrementRenderId = function () {
  25155. this._renderId++;
  25156. };
  25157. Scene.prototype._updatePointerPosition = function (evt) {
  25158. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25159. if (!canvasRect) {
  25160. return;
  25161. }
  25162. this._pointerX = evt.clientX - canvasRect.left;
  25163. this._pointerY = evt.clientY - canvasRect.top;
  25164. this._unTranslatedPointerX = this._pointerX;
  25165. this._unTranslatedPointerY = this._pointerY;
  25166. };
  25167. Scene.prototype._createUbo = function () {
  25168. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25169. this._sceneUbo.addUniform("viewProjection", 16);
  25170. this._sceneUbo.addUniform("view", 16);
  25171. };
  25172. Scene.prototype._createAlternateUbo = function () {
  25173. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25174. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25175. this._alternateSceneUbo.addUniform("view", 16);
  25176. };
  25177. // Pointers handling
  25178. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25179. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25180. if (result) {
  25181. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25182. }
  25183. return result;
  25184. };
  25185. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25186. if (pointerInfo.pickInfo) {
  25187. if (!pointerInfo.pickInfo.ray) {
  25188. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25189. }
  25190. }
  25191. };
  25192. /**
  25193. * Use this method to simulate a pointer move on a mesh
  25194. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25195. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25196. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25197. * @returns the current scene
  25198. */
  25199. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25200. var evt = new PointerEvent("pointermove", pointerEventInit);
  25201. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25202. return this;
  25203. }
  25204. return this._processPointerMove(pickResult, evt);
  25205. };
  25206. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25207. var canvas = this._engine.getRenderingCanvas();
  25208. if (!canvas) {
  25209. return this;
  25210. }
  25211. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25212. this.setPointerOverSprite(null);
  25213. this.setPointerOverMesh(pickResult.pickedMesh);
  25214. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25215. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25216. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25217. }
  25218. else {
  25219. canvas.style.cursor = this.hoverCursor;
  25220. }
  25221. }
  25222. else {
  25223. canvas.style.cursor = this.defaultCursor;
  25224. }
  25225. }
  25226. else {
  25227. this.setPointerOverMesh(null);
  25228. // Sprites
  25229. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25230. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25231. this.setPointerOverSprite(pickResult.pickedSprite);
  25232. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25233. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25234. }
  25235. else {
  25236. canvas.style.cursor = this.hoverCursor;
  25237. }
  25238. }
  25239. else {
  25240. this.setPointerOverSprite(null);
  25241. // Restore pointer
  25242. canvas.style.cursor = this.defaultCursor;
  25243. }
  25244. }
  25245. if (pickResult) {
  25246. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25247. if (this.onPointerMove) {
  25248. this.onPointerMove(evt, pickResult, type);
  25249. }
  25250. if (this.onPointerObservable.hasObservers()) {
  25251. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25252. this._setRayOnPointerInfo(pi);
  25253. this.onPointerObservable.notifyObservers(pi, type);
  25254. }
  25255. }
  25256. return this;
  25257. };
  25258. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25259. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25260. if (pickResult) {
  25261. pi.ray = pickResult.ray;
  25262. }
  25263. this.onPrePointerObservable.notifyObservers(pi, type);
  25264. if (pi.skipOnPointerObservable) {
  25265. return true;
  25266. }
  25267. else {
  25268. return false;
  25269. }
  25270. };
  25271. /**
  25272. * Use this method to simulate a pointer down on a mesh
  25273. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25274. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25275. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25276. * @returns the current scene
  25277. */
  25278. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25279. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25280. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25281. return this;
  25282. }
  25283. return this._processPointerDown(pickResult, evt);
  25284. };
  25285. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25286. var _this = this;
  25287. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25288. this._pickedDownMesh = pickResult.pickedMesh;
  25289. var actionManager = pickResult.pickedMesh.actionManager;
  25290. if (actionManager) {
  25291. if (actionManager.hasPickTriggers) {
  25292. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25293. switch (evt.button) {
  25294. case 0:
  25295. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25296. break;
  25297. case 1:
  25298. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25299. break;
  25300. case 2:
  25301. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25302. break;
  25303. }
  25304. }
  25305. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25306. window.setTimeout(function () {
  25307. 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);
  25308. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25309. if (_this._totalPointersPressed !== 0 &&
  25310. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25311. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25312. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25313. _this._startingPointerTime = 0;
  25314. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25315. }
  25316. }
  25317. }, Scene.LongPressDelay);
  25318. }
  25319. }
  25320. }
  25321. if (pickResult) {
  25322. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25323. if (this.onPointerDown) {
  25324. this.onPointerDown(evt, pickResult, type);
  25325. }
  25326. if (this.onPointerObservable.hasObservers()) {
  25327. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25328. this._setRayOnPointerInfo(pi);
  25329. this.onPointerObservable.notifyObservers(pi, type);
  25330. }
  25331. }
  25332. return this;
  25333. };
  25334. /**
  25335. * Use this method to simulate a pointer up on a mesh
  25336. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25337. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25338. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25339. * @returns the current scene
  25340. */
  25341. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25342. var evt = new PointerEvent("pointerup", pointerEventInit);
  25343. var clickInfo = new ClickInfo();
  25344. clickInfo.singleClick = true;
  25345. clickInfo.ignore = true;
  25346. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25347. return this;
  25348. }
  25349. return this._processPointerUp(pickResult, evt, clickInfo);
  25350. };
  25351. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25352. if (pickResult && pickResult && pickResult.pickedMesh) {
  25353. this._pickedUpMesh = pickResult.pickedMesh;
  25354. if (this._pickedDownMesh === this._pickedUpMesh) {
  25355. if (this.onPointerPick) {
  25356. this.onPointerPick(evt, pickResult);
  25357. }
  25358. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25359. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25360. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25361. this._setRayOnPointerInfo(pi);
  25362. this.onPointerObservable.notifyObservers(pi, type_1);
  25363. }
  25364. }
  25365. if (pickResult.pickedMesh.actionManager) {
  25366. if (clickInfo.ignore) {
  25367. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25368. }
  25369. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25370. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25371. }
  25372. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25373. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25374. }
  25375. }
  25376. }
  25377. if (this._pickedDownMesh &&
  25378. this._pickedDownMesh.actionManager &&
  25379. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25380. this._pickedDownMesh !== this._pickedUpMesh) {
  25381. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25382. }
  25383. var type = BABYLON.PointerEventTypes.POINTERUP;
  25384. if (this.onPointerObservable.hasObservers()) {
  25385. if (!clickInfo.ignore) {
  25386. if (!clickInfo.hasSwiped) {
  25387. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25388. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25389. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25390. this._setRayOnPointerInfo(pi);
  25391. this.onPointerObservable.notifyObservers(pi, type_2);
  25392. }
  25393. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25394. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25395. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25396. this._setRayOnPointerInfo(pi);
  25397. this.onPointerObservable.notifyObservers(pi, type_3);
  25398. }
  25399. }
  25400. }
  25401. else {
  25402. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25403. this._setRayOnPointerInfo(pi);
  25404. this.onPointerObservable.notifyObservers(pi, type);
  25405. }
  25406. }
  25407. if (this.onPointerUp) {
  25408. this.onPointerUp(evt, pickResult, type);
  25409. }
  25410. return this;
  25411. };
  25412. /**
  25413. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25414. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25415. * @returns true if the pointer was captured
  25416. */
  25417. Scene.prototype.isPointerCaptured = function (pointerId) {
  25418. if (pointerId === void 0) { pointerId = 0; }
  25419. return this._pointerCaptures[pointerId];
  25420. };
  25421. /**
  25422. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25423. * @param attachUp defines if you want to attach events to pointerup
  25424. * @param attachDown defines if you want to attach events to pointerdown
  25425. * @param attachMove defines if you want to attach events to pointermove
  25426. */
  25427. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25428. var _this = this;
  25429. if (attachUp === void 0) { attachUp = true; }
  25430. if (attachDown === void 0) { attachDown = true; }
  25431. if (attachMove === void 0) { attachMove = true; }
  25432. this._initActionManager = function (act, clickInfo) {
  25433. if (!_this._meshPickProceed) {
  25434. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25435. _this._currentPickResult = pickResult;
  25436. if (pickResult) {
  25437. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25438. }
  25439. _this._meshPickProceed = true;
  25440. }
  25441. return act;
  25442. };
  25443. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25444. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25445. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25446. btn !== _this._previousButtonPressed) {
  25447. _this._doubleClickOccured = false;
  25448. clickInfo.singleClick = true;
  25449. clickInfo.ignore = false;
  25450. cb(clickInfo, _this._currentPickResult);
  25451. }
  25452. };
  25453. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25454. var clickInfo = new ClickInfo();
  25455. _this._currentPickResult = null;
  25456. var act = null;
  25457. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25458. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25459. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25460. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25461. act = _this._initActionManager(act, clickInfo);
  25462. if (act)
  25463. checkPicking = act.hasPickTriggers;
  25464. }
  25465. if (checkPicking) {
  25466. var btn = evt.button;
  25467. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25468. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25469. if (!clickInfo.hasSwiped) {
  25470. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25471. if (!checkSingleClickImmediately) {
  25472. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25473. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25474. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25475. act = _this._initActionManager(act, clickInfo);
  25476. if (act)
  25477. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25478. }
  25479. }
  25480. if (checkSingleClickImmediately) {
  25481. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25482. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25483. btn !== _this._previousButtonPressed) {
  25484. clickInfo.singleClick = true;
  25485. cb(clickInfo, _this._currentPickResult);
  25486. }
  25487. }
  25488. // at least one double click is required to be check and exclusive double click is enabled
  25489. else {
  25490. // wait that no double click has been raised during the double click delay
  25491. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25492. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25493. }
  25494. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25495. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25496. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25497. act = _this._initActionManager(act, clickInfo);
  25498. if (act)
  25499. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25500. }
  25501. if (checkDoubleClick) {
  25502. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25503. if (btn === _this._previousButtonPressed &&
  25504. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25505. !_this._doubleClickOccured) {
  25506. // pointer has not moved for 2 clicks, it's a double click
  25507. if (!clickInfo.hasSwiped &&
  25508. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25509. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25510. _this._previousStartingPointerTime = 0;
  25511. _this._doubleClickOccured = true;
  25512. clickInfo.doubleClick = true;
  25513. clickInfo.ignore = false;
  25514. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25515. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25516. }
  25517. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25518. cb(clickInfo, _this._currentPickResult);
  25519. }
  25520. // if the two successive clicks are too far, it's just two simple clicks
  25521. else {
  25522. _this._doubleClickOccured = false;
  25523. _this._previousStartingPointerTime = _this._startingPointerTime;
  25524. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25525. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25526. _this._previousButtonPressed = btn;
  25527. if (Scene.ExclusiveDoubleClickMode) {
  25528. if (_this._previousDelayedSimpleClickTimeout) {
  25529. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25530. }
  25531. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25532. cb(clickInfo, _this._previousPickResult);
  25533. }
  25534. else {
  25535. cb(clickInfo, _this._currentPickResult);
  25536. }
  25537. }
  25538. }
  25539. // just the first click of the double has been raised
  25540. else {
  25541. _this._doubleClickOccured = false;
  25542. _this._previousStartingPointerTime = _this._startingPointerTime;
  25543. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25544. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25545. _this._previousButtonPressed = btn;
  25546. }
  25547. }
  25548. }
  25549. }
  25550. clickInfo.ignore = true;
  25551. cb(clickInfo, _this._currentPickResult);
  25552. };
  25553. this._spritePredicate = function (sprite) {
  25554. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25555. };
  25556. this._onPointerMove = function (evt) {
  25557. _this._updatePointerPosition(evt);
  25558. // PreObservable support
  25559. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25560. return;
  25561. }
  25562. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25563. return;
  25564. }
  25565. if (!_this.pointerMovePredicate) {
  25566. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25567. }
  25568. // Meshes
  25569. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25570. _this._processPointerMove(pickResult, evt);
  25571. };
  25572. this._onPointerDown = function (evt) {
  25573. _this._totalPointersPressed++;
  25574. _this._pickedDownMesh = null;
  25575. _this._meshPickProceed = false;
  25576. _this._updatePointerPosition(evt);
  25577. if (_this.preventDefaultOnPointerDown && canvas) {
  25578. evt.preventDefault();
  25579. canvas.focus();
  25580. }
  25581. // PreObservable support
  25582. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25583. return;
  25584. }
  25585. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25586. return;
  25587. }
  25588. _this._pointerCaptures[evt.pointerId] = true;
  25589. _this._startingPointerPosition.x = _this._pointerX;
  25590. _this._startingPointerPosition.y = _this._pointerY;
  25591. _this._startingPointerTime = Date.now();
  25592. if (!_this.pointerDownPredicate) {
  25593. _this.pointerDownPredicate = function (mesh) {
  25594. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25595. };
  25596. }
  25597. // Meshes
  25598. _this._pickedDownMesh = null;
  25599. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25600. _this._processPointerDown(pickResult, evt);
  25601. // Sprites
  25602. _this._pickedDownSprite = null;
  25603. if (_this.spriteManagers.length > 0) {
  25604. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25605. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25606. if (pickResult.pickedSprite.actionManager) {
  25607. _this._pickedDownSprite = pickResult.pickedSprite;
  25608. switch (evt.button) {
  25609. case 0:
  25610. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25611. break;
  25612. case 1:
  25613. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25614. break;
  25615. case 2:
  25616. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25617. break;
  25618. }
  25619. if (pickResult.pickedSprite.actionManager) {
  25620. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25621. }
  25622. }
  25623. }
  25624. }
  25625. };
  25626. this._onPointerUp = function (evt) {
  25627. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25628. return; // So we need to test it the pointer down was pressed before.
  25629. }
  25630. _this._totalPointersPressed--;
  25631. _this._pickedUpMesh = null;
  25632. _this._meshPickProceed = false;
  25633. _this._updatePointerPosition(evt);
  25634. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25635. // PreObservable support
  25636. if (_this.onPrePointerObservable.hasObservers()) {
  25637. if (!clickInfo.ignore) {
  25638. if (!clickInfo.hasSwiped) {
  25639. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25640. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25641. return;
  25642. }
  25643. }
  25644. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25645. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25646. return;
  25647. }
  25648. }
  25649. }
  25650. }
  25651. else {
  25652. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25653. return;
  25654. }
  25655. }
  25656. }
  25657. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25658. return;
  25659. }
  25660. _this._pointerCaptures[evt.pointerId] = false;
  25661. if (!_this.pointerUpPredicate) {
  25662. _this.pointerUpPredicate = function (mesh) {
  25663. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25664. };
  25665. }
  25666. // Meshes
  25667. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25668. _this._initActionManager(null, clickInfo);
  25669. }
  25670. if (!pickResult) {
  25671. pickResult = _this._currentPickResult;
  25672. }
  25673. _this._processPointerUp(pickResult, evt, clickInfo);
  25674. // Sprites
  25675. if (!clickInfo.ignore) {
  25676. if (_this.spriteManagers.length > 0) {
  25677. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25678. if (spritePickResult) {
  25679. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25680. if (spritePickResult.pickedSprite.actionManager) {
  25681. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25682. if (spritePickResult.pickedSprite.actionManager) {
  25683. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25684. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25685. }
  25686. }
  25687. }
  25688. }
  25689. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25690. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25691. }
  25692. }
  25693. }
  25694. }
  25695. _this._previousPickResult = _this._currentPickResult;
  25696. });
  25697. };
  25698. this._onKeyDown = function (evt) {
  25699. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25700. if (_this.onPreKeyboardObservable.hasObservers()) {
  25701. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25702. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25703. if (pi.skipOnPointerObservable) {
  25704. return;
  25705. }
  25706. }
  25707. if (_this.onKeyboardObservable.hasObservers()) {
  25708. var pi = new BABYLON.KeyboardInfo(type, evt);
  25709. _this.onKeyboardObservable.notifyObservers(pi, type);
  25710. }
  25711. if (_this.actionManager) {
  25712. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25713. }
  25714. };
  25715. this._onKeyUp = function (evt) {
  25716. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25717. if (_this.onPreKeyboardObservable.hasObservers()) {
  25718. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25719. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25720. if (pi.skipOnPointerObservable) {
  25721. return;
  25722. }
  25723. }
  25724. if (_this.onKeyboardObservable.hasObservers()) {
  25725. var pi = new BABYLON.KeyboardInfo(type, evt);
  25726. _this.onKeyboardObservable.notifyObservers(pi, type);
  25727. }
  25728. if (_this.actionManager) {
  25729. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25730. }
  25731. };
  25732. var engine = this.getEngine();
  25733. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25734. if (!canvas) {
  25735. return;
  25736. }
  25737. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25738. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25739. });
  25740. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25741. if (!canvas) {
  25742. return;
  25743. }
  25744. canvas.removeEventListener("keydown", _this._onKeyDown);
  25745. canvas.removeEventListener("keyup", _this._onKeyUp);
  25746. });
  25747. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25748. var canvas = this._engine.getRenderingCanvas();
  25749. if (!canvas) {
  25750. return;
  25751. }
  25752. if (attachMove) {
  25753. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25754. // Wheel
  25755. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25756. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25757. }
  25758. if (attachDown) {
  25759. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25760. }
  25761. if (attachUp) {
  25762. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25763. }
  25764. canvas.tabIndex = 1;
  25765. };
  25766. /** Detaches all event handlers*/
  25767. Scene.prototype.detachControl = function () {
  25768. var engine = this.getEngine();
  25769. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25770. var canvas = engine.getRenderingCanvas();
  25771. if (!canvas) {
  25772. return;
  25773. }
  25774. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25775. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25776. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25777. if (this._onCanvasBlurObserver) {
  25778. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25779. }
  25780. if (this._onCanvasFocusObserver) {
  25781. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25782. }
  25783. // Wheel
  25784. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25785. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25786. // Keyboard
  25787. canvas.removeEventListener("keydown", this._onKeyDown);
  25788. canvas.removeEventListener("keyup", this._onKeyUp);
  25789. // Observables
  25790. this.onKeyboardObservable.clear();
  25791. this.onPreKeyboardObservable.clear();
  25792. this.onPointerObservable.clear();
  25793. this.onPrePointerObservable.clear();
  25794. };
  25795. /**
  25796. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25797. * Delay loaded resources are not taking in account
  25798. * @return true if all required resources are ready
  25799. */
  25800. Scene.prototype.isReady = function () {
  25801. if (this._isDisposed) {
  25802. return false;
  25803. }
  25804. if (this._pendingData.length > 0) {
  25805. return false;
  25806. }
  25807. var index;
  25808. var engine = this.getEngine();
  25809. // Geometries
  25810. for (index = 0; index < this.geometries.length; index++) {
  25811. var geometry = this.geometries[index];
  25812. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25813. return false;
  25814. }
  25815. }
  25816. // Meshes
  25817. for (index = 0; index < this.meshes.length; index++) {
  25818. var mesh = this.meshes[index];
  25819. if (!mesh.isEnabled()) {
  25820. continue;
  25821. }
  25822. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25823. continue;
  25824. }
  25825. if (!mesh.isReady(true)) {
  25826. return false;
  25827. }
  25828. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25829. // Is Ready For Mesh
  25830. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25831. var step = _a[_i];
  25832. if (!step.action(mesh, hardwareInstancedRendering)) {
  25833. return false;
  25834. }
  25835. }
  25836. }
  25837. // Post-processes
  25838. if (this.activeCameras && this.activeCameras.length > 0) {
  25839. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25840. var camera = _c[_b];
  25841. if (!camera.isReady(true)) {
  25842. return false;
  25843. }
  25844. }
  25845. }
  25846. else if (this.activeCamera) {
  25847. if (!this.activeCamera.isReady(true)) {
  25848. return false;
  25849. }
  25850. }
  25851. // Particles
  25852. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25853. var particleSystem = _e[_d];
  25854. if (!particleSystem.isReady()) {
  25855. return false;
  25856. }
  25857. }
  25858. return true;
  25859. };
  25860. /** Resets all cached information relative to material (including effect and visibility) */
  25861. Scene.prototype.resetCachedMaterial = function () {
  25862. this._cachedMaterial = null;
  25863. this._cachedEffect = null;
  25864. this._cachedVisibility = null;
  25865. };
  25866. /**
  25867. * Registers a function to be called before every frame render
  25868. * @param func defines the function to register
  25869. */
  25870. Scene.prototype.registerBeforeRender = function (func) {
  25871. this.onBeforeRenderObservable.add(func);
  25872. };
  25873. /**
  25874. * Unregisters a function called before every frame render
  25875. * @param func defines the function to unregister
  25876. */
  25877. Scene.prototype.unregisterBeforeRender = function (func) {
  25878. this.onBeforeRenderObservable.removeCallback(func);
  25879. };
  25880. /**
  25881. * Registers a function to be called after every frame render
  25882. * @param func defines the function to register
  25883. */
  25884. Scene.prototype.registerAfterRender = function (func) {
  25885. this.onAfterRenderObservable.add(func);
  25886. };
  25887. /**
  25888. * Unregisters a function called after every frame render
  25889. * @param func defines the function to unregister
  25890. */
  25891. Scene.prototype.unregisterAfterRender = function (func) {
  25892. this.onAfterRenderObservable.removeCallback(func);
  25893. };
  25894. Scene.prototype._executeOnceBeforeRender = function (func) {
  25895. var _this = this;
  25896. var execFunc = function () {
  25897. func();
  25898. setTimeout(function () {
  25899. _this.unregisterBeforeRender(execFunc);
  25900. });
  25901. };
  25902. this.registerBeforeRender(execFunc);
  25903. };
  25904. /**
  25905. * The provided function will run before render once and will be disposed afterwards.
  25906. * A timeout delay can be provided so that the function will be executed in N ms.
  25907. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25908. * @param func The function to be executed.
  25909. * @param timeout optional delay in ms
  25910. */
  25911. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25912. var _this = this;
  25913. if (timeout !== undefined) {
  25914. setTimeout(function () {
  25915. _this._executeOnceBeforeRender(func);
  25916. }, timeout);
  25917. }
  25918. else {
  25919. this._executeOnceBeforeRender(func);
  25920. }
  25921. };
  25922. /** @hidden */
  25923. Scene.prototype._addPendingData = function (data) {
  25924. this._pendingData.push(data);
  25925. };
  25926. /** @hidden */
  25927. Scene.prototype._removePendingData = function (data) {
  25928. var wasLoading = this.isLoading;
  25929. var index = this._pendingData.indexOf(data);
  25930. if (index !== -1) {
  25931. this._pendingData.splice(index, 1);
  25932. }
  25933. if (wasLoading && !this.isLoading) {
  25934. this.onDataLoadedObservable.notifyObservers(this);
  25935. }
  25936. };
  25937. /**
  25938. * Returns the number of items waiting to be loaded
  25939. * @returns the number of items waiting to be loaded
  25940. */
  25941. Scene.prototype.getWaitingItemsCount = function () {
  25942. return this._pendingData.length;
  25943. };
  25944. Object.defineProperty(Scene.prototype, "isLoading", {
  25945. /**
  25946. * Returns a boolean indicating if the scene is still loading data
  25947. */
  25948. get: function () {
  25949. return this._pendingData.length > 0;
  25950. },
  25951. enumerable: true,
  25952. configurable: true
  25953. });
  25954. /**
  25955. * Registers a function to be executed when the scene is ready
  25956. * @param {Function} func - the function to be executed
  25957. */
  25958. Scene.prototype.executeWhenReady = function (func) {
  25959. var _this = this;
  25960. this.onReadyObservable.add(func);
  25961. if (this._executeWhenReadyTimeoutId !== -1) {
  25962. return;
  25963. }
  25964. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25965. _this._checkIsReady();
  25966. }, 150);
  25967. };
  25968. /**
  25969. * Returns a promise that resolves when the scene is ready
  25970. * @returns A promise that resolves when the scene is ready
  25971. */
  25972. Scene.prototype.whenReadyAsync = function () {
  25973. var _this = this;
  25974. return new Promise(function (resolve) {
  25975. _this.executeWhenReady(function () {
  25976. resolve();
  25977. });
  25978. });
  25979. };
  25980. /** @hidden */
  25981. Scene.prototype._checkIsReady = function () {
  25982. var _this = this;
  25983. this._registerTransientComponents();
  25984. if (this.isReady()) {
  25985. this.onReadyObservable.notifyObservers(this);
  25986. this.onReadyObservable.clear();
  25987. this._executeWhenReadyTimeoutId = -1;
  25988. return;
  25989. }
  25990. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25991. _this._checkIsReady();
  25992. }, 150);
  25993. };
  25994. // Animations
  25995. /**
  25996. * Will start the animation sequence of a given target
  25997. * @param target defines the target
  25998. * @param from defines from which frame should animation start
  25999. * @param to defines until which frame should animation run.
  26000. * @param weight defines the weight to apply to the animation (1.0 by default)
  26001. * @param loop defines if the animation loops
  26002. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26003. * @param onAnimationEnd defines the function to be executed when the animation ends
  26004. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26005. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26006. * @returns the animatable object created for this animation
  26007. */
  26008. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  26009. if (weight === void 0) { weight = 1.0; }
  26010. if (speedRatio === void 0) { speedRatio = 1.0; }
  26011. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  26012. returnedAnimatable.weight = weight;
  26013. return returnedAnimatable;
  26014. };
  26015. /**
  26016. * Will start the animation sequence of a given target
  26017. * @param target defines the target
  26018. * @param from defines from which frame should animation start
  26019. * @param to defines until which frame should animation run.
  26020. * @param loop defines if the animation loops
  26021. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26022. * @param onAnimationEnd defines the function to be executed when the animation ends
  26023. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26024. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26025. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26026. * @returns the animatable object created for this animation
  26027. */
  26028. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  26029. if (speedRatio === void 0) { speedRatio = 1.0; }
  26030. if (stopCurrent === void 0) { stopCurrent = true; }
  26031. if (from > to && speedRatio > 0) {
  26032. speedRatio *= -1;
  26033. }
  26034. if (stopCurrent) {
  26035. this.stopAnimation(target, undefined, targetMask);
  26036. }
  26037. if (!animatable) {
  26038. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26039. }
  26040. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26041. // Local animations
  26042. if (target.animations && shouldRunTargetAnimations) {
  26043. animatable.appendAnimations(target, target.animations);
  26044. }
  26045. // Children animations
  26046. if (target.getAnimatables) {
  26047. var animatables = target.getAnimatables();
  26048. for (var index = 0; index < animatables.length; index++) {
  26049. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26050. }
  26051. }
  26052. animatable.reset();
  26053. return animatable;
  26054. };
  26055. /**
  26056. * Begin a new animation on a given node
  26057. * @param target defines the target where the animation will take place
  26058. * @param animations defines the list of animations to start
  26059. * @param from defines the initial value
  26060. * @param to defines the final value
  26061. * @param loop defines if you want animation to loop (off by default)
  26062. * @param speedRatio defines the speed ratio to apply to all animations
  26063. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26064. * @returns the list of created animatables
  26065. */
  26066. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26067. if (speedRatio === undefined) {
  26068. speedRatio = 1.0;
  26069. }
  26070. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26071. return animatable;
  26072. };
  26073. /**
  26074. * Begin a new animation on a given node and its hierarchy
  26075. * @param target defines the root node where the animation will take place
  26076. * @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.
  26077. * @param animations defines the list of animations to start
  26078. * @param from defines the initial value
  26079. * @param to defines the final value
  26080. * @param loop defines if you want animation to loop (off by default)
  26081. * @param speedRatio defines the speed ratio to apply to all animations
  26082. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26083. * @returns the list of animatables created for all nodes
  26084. */
  26085. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26086. var children = target.getDescendants(directDescendantsOnly);
  26087. var result = [];
  26088. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26089. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26090. var child = children_1[_i];
  26091. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26092. }
  26093. return result;
  26094. };
  26095. /**
  26096. * Gets the animatable associated with a specific target
  26097. * @param target defines the target of the animatable
  26098. * @returns the required animatable if found
  26099. */
  26100. Scene.prototype.getAnimatableByTarget = function (target) {
  26101. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26102. if (this._activeAnimatables[index].target === target) {
  26103. return this._activeAnimatables[index];
  26104. }
  26105. }
  26106. return null;
  26107. };
  26108. /**
  26109. * Gets all animatables associated with a given target
  26110. * @param target defines the target to look animatables for
  26111. * @returns an array of Animatables
  26112. */
  26113. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26114. var result = [];
  26115. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26116. if (this._activeAnimatables[index].target === target) {
  26117. result.push(this._activeAnimatables[index]);
  26118. }
  26119. }
  26120. return result;
  26121. };
  26122. Object.defineProperty(Scene.prototype, "animatables", {
  26123. /**
  26124. * Gets all animatable attached to the scene
  26125. */
  26126. get: function () {
  26127. return this._activeAnimatables;
  26128. },
  26129. enumerable: true,
  26130. configurable: true
  26131. });
  26132. /**
  26133. * Will stop the animation of the given target
  26134. * @param target - the target
  26135. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26136. * @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)
  26137. */
  26138. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26139. var animatables = this.getAllAnimatablesByTarget(target);
  26140. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26141. var animatable = animatables_1[_i];
  26142. animatable.stop(animationName, targetMask);
  26143. }
  26144. };
  26145. /**
  26146. * Stops and removes all animations that have been applied to the scene
  26147. */
  26148. Scene.prototype.stopAllAnimations = function () {
  26149. if (this._activeAnimatables) {
  26150. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26151. this._activeAnimatables[i].stop();
  26152. }
  26153. this._activeAnimatables = [];
  26154. }
  26155. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26156. var group = _a[_i];
  26157. group.stop();
  26158. }
  26159. };
  26160. Scene.prototype._animate = function () {
  26161. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26162. return;
  26163. }
  26164. // Getting time
  26165. var now = BABYLON.Tools.Now;
  26166. if (!this._animationTimeLast) {
  26167. if (this._pendingData.length > 0) {
  26168. return;
  26169. }
  26170. this._animationTimeLast = now;
  26171. }
  26172. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26173. this._animationTime += deltaTime;
  26174. this._animationTimeLast = now;
  26175. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26176. this._activeAnimatables[index]._animate(this._animationTime);
  26177. }
  26178. // Late animation bindings
  26179. this._processLateAnimationBindings();
  26180. };
  26181. /** @hidden */
  26182. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26183. var target = runtimeAnimation.target;
  26184. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26185. if (!target._lateAnimationHolders) {
  26186. target._lateAnimationHolders = {};
  26187. }
  26188. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26189. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26190. totalWeight: 0,
  26191. animations: [],
  26192. originalValue: originalValue
  26193. };
  26194. }
  26195. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26196. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26197. };
  26198. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26199. var normalizer = 1.0;
  26200. var finalPosition = BABYLON.Tmp.Vector3[0];
  26201. var finalScaling = BABYLON.Tmp.Vector3[1];
  26202. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26203. var startIndex = 0;
  26204. var originalAnimation = holder.animations[0];
  26205. var originalValue = holder.originalValue;
  26206. var scale = 1;
  26207. if (holder.totalWeight < 1.0) {
  26208. // We need to mix the original value in
  26209. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26210. scale = 1.0 - holder.totalWeight;
  26211. }
  26212. else {
  26213. startIndex = 1;
  26214. // We need to normalize the weights
  26215. normalizer = holder.totalWeight;
  26216. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26217. scale = originalAnimation.weight / normalizer;
  26218. if (scale == 1) {
  26219. return originalAnimation.currentValue;
  26220. }
  26221. }
  26222. finalScaling.scaleInPlace(scale);
  26223. finalPosition.scaleInPlace(scale);
  26224. finalQuaternion.scaleInPlace(scale);
  26225. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26226. var runtimeAnimation = holder.animations[animIndex];
  26227. var scale = runtimeAnimation.weight / normalizer;
  26228. var currentPosition = BABYLON.Tmp.Vector3[2];
  26229. var currentScaling = BABYLON.Tmp.Vector3[3];
  26230. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26231. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26232. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26233. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26234. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26235. }
  26236. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26237. return originalAnimation._workValue;
  26238. };
  26239. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  26240. var originalAnimation = holder.animations[0];
  26241. var originalValue = holder.originalValue;
  26242. if (holder.animations.length === 1) {
  26243. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  26244. return refQuaternion;
  26245. }
  26246. var normalizer = 1.0;
  26247. var quaternions;
  26248. var weights;
  26249. if (holder.totalWeight < 1.0) {
  26250. var scale = 1.0 - holder.totalWeight;
  26251. quaternions = [];
  26252. weights = [];
  26253. quaternions.push(originalValue);
  26254. weights.push(scale);
  26255. }
  26256. else {
  26257. if (holder.animations.length === 2) { // Slerp as soon as we can
  26258. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  26259. return refQuaternion;
  26260. }
  26261. quaternions = [];
  26262. weights = [];
  26263. normalizer = holder.totalWeight;
  26264. }
  26265. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26266. var runtimeAnimation = holder.animations[animIndex];
  26267. quaternions.push(runtimeAnimation.currentValue);
  26268. weights.push(runtimeAnimation.weight / normalizer);
  26269. }
  26270. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26271. var cumulativeAmount = 0;
  26272. var cumulativeQuaternion = null;
  26273. for (var index = 0; index < quaternions.length;) {
  26274. if (!cumulativeQuaternion) {
  26275. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  26276. cumulativeQuaternion = refQuaternion;
  26277. cumulativeAmount = weights[index] + weights[index + 1];
  26278. index += 2;
  26279. continue;
  26280. }
  26281. cumulativeAmount += weights[index];
  26282. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26283. index++;
  26284. }
  26285. return cumulativeQuaternion;
  26286. };
  26287. Scene.prototype._processLateAnimationBindings = function () {
  26288. if (!this._registeredForLateAnimationBindings.length) {
  26289. return;
  26290. }
  26291. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26292. var target = this._registeredForLateAnimationBindings.data[index];
  26293. for (var path in target._lateAnimationHolders) {
  26294. var holder = target._lateAnimationHolders[path];
  26295. var originalAnimation = holder.animations[0];
  26296. var originalValue = holder.originalValue;
  26297. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26298. var finalValue = target[path];
  26299. if (matrixDecomposeMode) {
  26300. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26301. }
  26302. else {
  26303. var quaternionMode = originalValue.w !== undefined;
  26304. if (quaternionMode) {
  26305. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  26306. }
  26307. else {
  26308. var startIndex = 0;
  26309. var normalizer = 1.0;
  26310. if (holder.totalWeight < 1.0) {
  26311. // We need to mix the original value in
  26312. if (originalValue.scale) {
  26313. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26314. }
  26315. else {
  26316. finalValue = originalValue * (1.0 - holder.totalWeight);
  26317. }
  26318. }
  26319. else {
  26320. // We need to normalize the weights
  26321. normalizer = holder.totalWeight;
  26322. var scale_1 = originalAnimation.weight / normalizer;
  26323. if (scale_1 !== 1) {
  26324. if (originalAnimation.currentValue.scale) {
  26325. finalValue = originalAnimation.currentValue.scale(scale_1);
  26326. }
  26327. else {
  26328. finalValue = originalAnimation.currentValue * scale_1;
  26329. }
  26330. }
  26331. else {
  26332. finalValue = originalAnimation.currentValue;
  26333. }
  26334. startIndex = 1;
  26335. }
  26336. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26337. var runtimeAnimation = holder.animations[animIndex];
  26338. var scale = runtimeAnimation.weight / normalizer;
  26339. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26340. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26341. }
  26342. else {
  26343. finalValue += runtimeAnimation.currentValue * scale;
  26344. }
  26345. }
  26346. }
  26347. }
  26348. target[path] = finalValue;
  26349. }
  26350. target._lateAnimationHolders = {};
  26351. }
  26352. this._registeredForLateAnimationBindings.reset();
  26353. };
  26354. // Matrix
  26355. /** @hidden */
  26356. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26357. this._useAlternateCameraConfiguration = active;
  26358. };
  26359. /**
  26360. * Gets the current view matrix
  26361. * @returns a Matrix
  26362. */
  26363. Scene.prototype.getViewMatrix = function () {
  26364. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26365. };
  26366. /**
  26367. * Gets the current projection matrix
  26368. * @returns a Matrix
  26369. */
  26370. Scene.prototype.getProjectionMatrix = function () {
  26371. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26372. };
  26373. /**
  26374. * Gets the current transform matrix
  26375. * @returns a Matrix made of View * Projection
  26376. */
  26377. Scene.prototype.getTransformMatrix = function () {
  26378. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26379. };
  26380. /**
  26381. * Sets the current transform matrix
  26382. * @param view defines the View matrix to use
  26383. * @param projection defines the Projection matrix to use
  26384. */
  26385. Scene.prototype.setTransformMatrix = function (view, projection) {
  26386. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26387. return;
  26388. }
  26389. this._viewUpdateFlag = view.updateFlag;
  26390. this._projectionUpdateFlag = projection.updateFlag;
  26391. this._viewMatrix = view;
  26392. this._projectionMatrix = projection;
  26393. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26394. // Update frustum
  26395. if (!this._frustumPlanes) {
  26396. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26397. }
  26398. else {
  26399. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26400. }
  26401. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26402. var otherCamera = this.activeCamera._alternateCamera;
  26403. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26404. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26405. }
  26406. if (this._sceneUbo.useUbo) {
  26407. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26408. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26409. this._sceneUbo.update();
  26410. }
  26411. };
  26412. /** @hidden */
  26413. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26414. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26415. return;
  26416. }
  26417. this._alternateViewUpdateFlag = view.updateFlag;
  26418. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26419. this._alternateViewMatrix = view;
  26420. this._alternateProjectionMatrix = projection;
  26421. if (!this._alternateTransformMatrix) {
  26422. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26423. }
  26424. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26425. if (!this._alternateSceneUbo) {
  26426. this._createAlternateUbo();
  26427. }
  26428. if (this._alternateSceneUbo.useUbo) {
  26429. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26430. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26431. this._alternateSceneUbo.update();
  26432. }
  26433. };
  26434. /**
  26435. * Gets the uniform buffer used to store scene data
  26436. * @returns a UniformBuffer
  26437. */
  26438. Scene.prototype.getSceneUniformBuffer = function () {
  26439. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26440. };
  26441. /**
  26442. * Gets an unique (relatively to the current scene) Id
  26443. * @returns an unique number for the scene
  26444. */
  26445. Scene.prototype.getUniqueId = function () {
  26446. var result = Scene._uniqueIdCounter;
  26447. Scene._uniqueIdCounter++;
  26448. return result;
  26449. };
  26450. /**
  26451. * Add a mesh to the list of scene's meshes
  26452. * @param newMesh defines the mesh to add
  26453. * @param recursive if all child meshes should also be added to the scene
  26454. */
  26455. Scene.prototype.addMesh = function (newMesh, recursive) {
  26456. var _this = this;
  26457. if (recursive === void 0) { recursive = false; }
  26458. this.meshes.push(newMesh);
  26459. //notify the collision coordinator
  26460. if (this.collisionCoordinator) {
  26461. this.collisionCoordinator.onMeshAdded(newMesh);
  26462. }
  26463. newMesh._resyncLightSources();
  26464. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26465. if (recursive) {
  26466. newMesh.getChildMeshes().forEach(function (m) {
  26467. _this.addMesh(m);
  26468. });
  26469. }
  26470. };
  26471. /**
  26472. * Remove a mesh for the list of scene's meshes
  26473. * @param toRemove defines the mesh to remove
  26474. * @param recursive if all child meshes should also be removed from the scene
  26475. * @returns the index where the mesh was in the mesh list
  26476. */
  26477. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26478. var _this = this;
  26479. if (recursive === void 0) { recursive = false; }
  26480. var index = this.meshes.indexOf(toRemove);
  26481. if (index !== -1) {
  26482. // Remove from the scene if mesh found
  26483. this.meshes.splice(index, 1);
  26484. }
  26485. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26486. if (recursive) {
  26487. toRemove.getChildMeshes().forEach(function (m) {
  26488. _this.removeMesh(m);
  26489. });
  26490. }
  26491. return index;
  26492. };
  26493. /**
  26494. * Add a transform node to the list of scene's transform nodes
  26495. * @param newTransformNode defines the transform node to add
  26496. */
  26497. Scene.prototype.addTransformNode = function (newTransformNode) {
  26498. this.transformNodes.push(newTransformNode);
  26499. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26500. };
  26501. /**
  26502. * Remove a transform node for the list of scene's transform nodes
  26503. * @param toRemove defines the transform node to remove
  26504. * @returns the index where the transform node was in the transform node list
  26505. */
  26506. Scene.prototype.removeTransformNode = function (toRemove) {
  26507. var index = this.transformNodes.indexOf(toRemove);
  26508. if (index !== -1) {
  26509. // Remove from the scene if found
  26510. this.transformNodes.splice(index, 1);
  26511. }
  26512. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26513. return index;
  26514. };
  26515. /**
  26516. * Remove a skeleton for the list of scene's skeletons
  26517. * @param toRemove defines the skeleton to remove
  26518. * @returns the index where the skeleton was in the skeleton list
  26519. */
  26520. Scene.prototype.removeSkeleton = function (toRemove) {
  26521. var index = this.skeletons.indexOf(toRemove);
  26522. if (index !== -1) {
  26523. // Remove from the scene if found
  26524. this.skeletons.splice(index, 1);
  26525. }
  26526. return index;
  26527. };
  26528. /**
  26529. * Remove a morph target for the list of scene's morph targets
  26530. * @param toRemove defines the morph target to remove
  26531. * @returns the index where the morph target was in the morph target list
  26532. */
  26533. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26534. var index = this.morphTargetManagers.indexOf(toRemove);
  26535. if (index !== -1) {
  26536. // Remove from the scene if found
  26537. this.morphTargetManagers.splice(index, 1);
  26538. }
  26539. return index;
  26540. };
  26541. /**
  26542. * Remove a light for the list of scene's lights
  26543. * @param toRemove defines the light to remove
  26544. * @returns the index where the light was in the light list
  26545. */
  26546. Scene.prototype.removeLight = function (toRemove) {
  26547. var index = this.lights.indexOf(toRemove);
  26548. if (index !== -1) {
  26549. // Remove from meshes
  26550. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26551. var mesh = _a[_i];
  26552. mesh._removeLightSource(toRemove);
  26553. }
  26554. // Remove from the scene if mesh found
  26555. this.lights.splice(index, 1);
  26556. this.sortLightsByPriority();
  26557. }
  26558. this.onLightRemovedObservable.notifyObservers(toRemove);
  26559. return index;
  26560. };
  26561. /**
  26562. * Remove a camera for the list of scene's cameras
  26563. * @param toRemove defines the camera to remove
  26564. * @returns the index where the camera was in the camera list
  26565. */
  26566. Scene.prototype.removeCamera = function (toRemove) {
  26567. var index = this.cameras.indexOf(toRemove);
  26568. if (index !== -1) {
  26569. // Remove from the scene if mesh found
  26570. this.cameras.splice(index, 1);
  26571. }
  26572. // Remove from activeCameras
  26573. var index2 = this.activeCameras.indexOf(toRemove);
  26574. if (index2 !== -1) {
  26575. // Remove from the scene if mesh found
  26576. this.activeCameras.splice(index2, 1);
  26577. }
  26578. // Reset the activeCamera
  26579. if (this.activeCamera === toRemove) {
  26580. if (this.cameras.length > 0) {
  26581. this.activeCamera = this.cameras[0];
  26582. }
  26583. else {
  26584. this.activeCamera = null;
  26585. }
  26586. }
  26587. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26588. return index;
  26589. };
  26590. /**
  26591. * Remove a particle system for the list of scene's particle systems
  26592. * @param toRemove defines the particle system to remove
  26593. * @returns the index where the particle system was in the particle system list
  26594. */
  26595. Scene.prototype.removeParticleSystem = function (toRemove) {
  26596. var index = this.particleSystems.indexOf(toRemove);
  26597. if (index !== -1) {
  26598. this.particleSystems.splice(index, 1);
  26599. }
  26600. return index;
  26601. };
  26602. /**
  26603. * Remove a animation for the list of scene's animations
  26604. * @param toRemove defines the animation to remove
  26605. * @returns the index where the animation was in the animation list
  26606. */
  26607. Scene.prototype.removeAnimation = function (toRemove) {
  26608. var index = this.animations.indexOf(toRemove);
  26609. if (index !== -1) {
  26610. this.animations.splice(index, 1);
  26611. }
  26612. return index;
  26613. };
  26614. /**
  26615. * Removes the given animation group from this scene.
  26616. * @param toRemove The animation group to remove
  26617. * @returns The index of the removed animation group
  26618. */
  26619. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26620. var index = this.animationGroups.indexOf(toRemove);
  26621. if (index !== -1) {
  26622. this.animationGroups.splice(index, 1);
  26623. }
  26624. return index;
  26625. };
  26626. /**
  26627. * Removes the given multi-material from this scene.
  26628. * @param toRemove The multi-material to remove
  26629. * @returns The index of the removed multi-material
  26630. */
  26631. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26632. var index = this.multiMaterials.indexOf(toRemove);
  26633. if (index !== -1) {
  26634. this.multiMaterials.splice(index, 1);
  26635. }
  26636. return index;
  26637. };
  26638. /**
  26639. * Removes the given material from this scene.
  26640. * @param toRemove The material to remove
  26641. * @returns The index of the removed material
  26642. */
  26643. Scene.prototype.removeMaterial = function (toRemove) {
  26644. var index = this.materials.indexOf(toRemove);
  26645. if (index !== -1) {
  26646. this.materials.splice(index, 1);
  26647. }
  26648. return index;
  26649. };
  26650. /**
  26651. * Removes the given action manager from this scene.
  26652. * @param toRemove The action manager to remove
  26653. * @returns The index of the removed action manager
  26654. */
  26655. Scene.prototype.removeActionManager = function (toRemove) {
  26656. var index = this.actionManagers.indexOf(toRemove);
  26657. if (index !== -1) {
  26658. this.actionManagers.splice(index, 1);
  26659. }
  26660. return index;
  26661. };
  26662. /**
  26663. * Removes the given texture from this scene.
  26664. * @param toRemove The texture to remove
  26665. * @returns The index of the removed texture
  26666. */
  26667. Scene.prototype.removeTexture = function (toRemove) {
  26668. var index = this.textures.indexOf(toRemove);
  26669. if (index !== -1) {
  26670. this.textures.splice(index, 1);
  26671. }
  26672. return index;
  26673. };
  26674. /**
  26675. * Adds the given light to this scene
  26676. * @param newLight The light to add
  26677. */
  26678. Scene.prototype.addLight = function (newLight) {
  26679. this.lights.push(newLight);
  26680. this.sortLightsByPriority();
  26681. // Add light to all meshes (To support if the light is removed and then readded)
  26682. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26683. var mesh = _a[_i];
  26684. if (mesh._lightSources.indexOf(newLight) === -1) {
  26685. mesh._lightSources.push(newLight);
  26686. mesh._resyncLightSources();
  26687. }
  26688. }
  26689. this.onNewLightAddedObservable.notifyObservers(newLight);
  26690. };
  26691. /**
  26692. * Sorts the list list based on light priorities
  26693. */
  26694. Scene.prototype.sortLightsByPriority = function () {
  26695. if (this.requireLightSorting) {
  26696. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26697. }
  26698. };
  26699. /**
  26700. * Adds the given camera to this scene
  26701. * @param newCamera The camera to add
  26702. */
  26703. Scene.prototype.addCamera = function (newCamera) {
  26704. this.cameras.push(newCamera);
  26705. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26706. };
  26707. /**
  26708. * Adds the given skeleton to this scene
  26709. * @param newSkeleton The skeleton to add
  26710. */
  26711. Scene.prototype.addSkeleton = function (newSkeleton) {
  26712. this.skeletons.push(newSkeleton);
  26713. };
  26714. /**
  26715. * Adds the given particle system to this scene
  26716. * @param newParticleSystem The particle system to add
  26717. */
  26718. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26719. this.particleSystems.push(newParticleSystem);
  26720. };
  26721. /**
  26722. * Adds the given animation to this scene
  26723. * @param newAnimation The animation to add
  26724. */
  26725. Scene.prototype.addAnimation = function (newAnimation) {
  26726. this.animations.push(newAnimation);
  26727. };
  26728. /**
  26729. * Adds the given animation group to this scene.
  26730. * @param newAnimationGroup The animation group to add
  26731. */
  26732. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26733. this.animationGroups.push(newAnimationGroup);
  26734. };
  26735. /**
  26736. * Adds the given multi-material to this scene
  26737. * @param newMultiMaterial The multi-material to add
  26738. */
  26739. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26740. this.multiMaterials.push(newMultiMaterial);
  26741. };
  26742. /**
  26743. * Adds the given material to this scene
  26744. * @param newMaterial The material to add
  26745. */
  26746. Scene.prototype.addMaterial = function (newMaterial) {
  26747. this.materials.push(newMaterial);
  26748. };
  26749. /**
  26750. * Adds the given morph target to this scene
  26751. * @param newMorphTargetManager The morph target to add
  26752. */
  26753. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26754. this.morphTargetManagers.push(newMorphTargetManager);
  26755. };
  26756. /**
  26757. * Adds the given geometry to this scene
  26758. * @param newGeometry The geometry to add
  26759. */
  26760. Scene.prototype.addGeometry = function (newGeometry) {
  26761. this.geometries.push(newGeometry);
  26762. };
  26763. /**
  26764. * Adds the given action manager to this scene
  26765. * @param newActionManager The action manager to add
  26766. */
  26767. Scene.prototype.addActionManager = function (newActionManager) {
  26768. this.actionManagers.push(newActionManager);
  26769. };
  26770. /**
  26771. * Adds the given texture to this scene.
  26772. * @param newTexture The texture to add
  26773. */
  26774. Scene.prototype.addTexture = function (newTexture) {
  26775. this.textures.push(newTexture);
  26776. };
  26777. /**
  26778. * Switch active camera
  26779. * @param newCamera defines the new active camera
  26780. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26781. */
  26782. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26783. if (attachControl === void 0) { attachControl = true; }
  26784. var canvas = this._engine.getRenderingCanvas();
  26785. if (!canvas) {
  26786. return;
  26787. }
  26788. if (this.activeCamera) {
  26789. this.activeCamera.detachControl(canvas);
  26790. }
  26791. this.activeCamera = newCamera;
  26792. if (attachControl) {
  26793. newCamera.attachControl(canvas);
  26794. }
  26795. };
  26796. /**
  26797. * sets the active camera of the scene using its ID
  26798. * @param id defines the camera's ID
  26799. * @return the new active camera or null if none found.
  26800. */
  26801. Scene.prototype.setActiveCameraByID = function (id) {
  26802. var camera = this.getCameraByID(id);
  26803. if (camera) {
  26804. this.activeCamera = camera;
  26805. return camera;
  26806. }
  26807. return null;
  26808. };
  26809. /**
  26810. * sets the active camera of the scene using its name
  26811. * @param name defines the camera's name
  26812. * @returns the new active camera or null if none found.
  26813. */
  26814. Scene.prototype.setActiveCameraByName = function (name) {
  26815. var camera = this.getCameraByName(name);
  26816. if (camera) {
  26817. this.activeCamera = camera;
  26818. return camera;
  26819. }
  26820. return null;
  26821. };
  26822. /**
  26823. * get an animation group using its name
  26824. * @param name defines the material's name
  26825. * @return the animation group or null if none found.
  26826. */
  26827. Scene.prototype.getAnimationGroupByName = function (name) {
  26828. for (var index = 0; index < this.animationGroups.length; index++) {
  26829. if (this.animationGroups[index].name === name) {
  26830. return this.animationGroups[index];
  26831. }
  26832. }
  26833. return null;
  26834. };
  26835. /**
  26836. * get a material using its id
  26837. * @param id defines the material's ID
  26838. * @return the material or null if none found.
  26839. */
  26840. Scene.prototype.getMaterialByID = function (id) {
  26841. for (var index = 0; index < this.materials.length; index++) {
  26842. if (this.materials[index].id === id) {
  26843. return this.materials[index];
  26844. }
  26845. }
  26846. return null;
  26847. };
  26848. /**
  26849. * Gets a material using its name
  26850. * @param name defines the material's name
  26851. * @return the material or null if none found.
  26852. */
  26853. Scene.prototype.getMaterialByName = function (name) {
  26854. for (var index = 0; index < this.materials.length; index++) {
  26855. if (this.materials[index].name === name) {
  26856. return this.materials[index];
  26857. }
  26858. }
  26859. return null;
  26860. };
  26861. /**
  26862. * Gets a camera using its id
  26863. * @param id defines the id to look for
  26864. * @returns the camera or null if not found
  26865. */
  26866. Scene.prototype.getCameraByID = function (id) {
  26867. for (var index = 0; index < this.cameras.length; index++) {
  26868. if (this.cameras[index].id === id) {
  26869. return this.cameras[index];
  26870. }
  26871. }
  26872. return null;
  26873. };
  26874. /**
  26875. * Gets a camera using its unique id
  26876. * @param uniqueId defines the unique id to look for
  26877. * @returns the camera or null if not found
  26878. */
  26879. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26880. for (var index = 0; index < this.cameras.length; index++) {
  26881. if (this.cameras[index].uniqueId === uniqueId) {
  26882. return this.cameras[index];
  26883. }
  26884. }
  26885. return null;
  26886. };
  26887. /**
  26888. * Gets a camera using its name
  26889. * @param name defines the camera's name
  26890. * @return the camera or null if none found.
  26891. */
  26892. Scene.prototype.getCameraByName = function (name) {
  26893. for (var index = 0; index < this.cameras.length; index++) {
  26894. if (this.cameras[index].name === name) {
  26895. return this.cameras[index];
  26896. }
  26897. }
  26898. return null;
  26899. };
  26900. /**
  26901. * Gets a bone using its id
  26902. * @param id defines the bone's id
  26903. * @return the bone or null if not found
  26904. */
  26905. Scene.prototype.getBoneByID = function (id) {
  26906. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26907. var skeleton = this.skeletons[skeletonIndex];
  26908. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26909. if (skeleton.bones[boneIndex].id === id) {
  26910. return skeleton.bones[boneIndex];
  26911. }
  26912. }
  26913. }
  26914. return null;
  26915. };
  26916. /**
  26917. * Gets a bone using its id
  26918. * @param name defines the bone's name
  26919. * @return the bone or null if not found
  26920. */
  26921. Scene.prototype.getBoneByName = function (name) {
  26922. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26923. var skeleton = this.skeletons[skeletonIndex];
  26924. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26925. if (skeleton.bones[boneIndex].name === name) {
  26926. return skeleton.bones[boneIndex];
  26927. }
  26928. }
  26929. }
  26930. return null;
  26931. };
  26932. /**
  26933. * Gets a light node using its name
  26934. * @param name defines the the light's name
  26935. * @return the light or null if none found.
  26936. */
  26937. Scene.prototype.getLightByName = function (name) {
  26938. for (var index = 0; index < this.lights.length; index++) {
  26939. if (this.lights[index].name === name) {
  26940. return this.lights[index];
  26941. }
  26942. }
  26943. return null;
  26944. };
  26945. /**
  26946. * Gets a light node using its id
  26947. * @param id defines the light's id
  26948. * @return the light or null if none found.
  26949. */
  26950. Scene.prototype.getLightByID = function (id) {
  26951. for (var index = 0; index < this.lights.length; index++) {
  26952. if (this.lights[index].id === id) {
  26953. return this.lights[index];
  26954. }
  26955. }
  26956. return null;
  26957. };
  26958. /**
  26959. * Gets a light node using its scene-generated unique ID
  26960. * @param uniqueId defines the light's unique id
  26961. * @return the light or null if none found.
  26962. */
  26963. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26964. for (var index = 0; index < this.lights.length; index++) {
  26965. if (this.lights[index].uniqueId === uniqueId) {
  26966. return this.lights[index];
  26967. }
  26968. }
  26969. return null;
  26970. };
  26971. /**
  26972. * Gets a particle system by id
  26973. * @param id defines the particle system id
  26974. * @return the corresponding system or null if none found
  26975. */
  26976. Scene.prototype.getParticleSystemByID = function (id) {
  26977. for (var index = 0; index < this.particleSystems.length; index++) {
  26978. if (this.particleSystems[index].id === id) {
  26979. return this.particleSystems[index];
  26980. }
  26981. }
  26982. return null;
  26983. };
  26984. /**
  26985. * Gets a geometry using its ID
  26986. * @param id defines the geometry's id
  26987. * @return the geometry or null if none found.
  26988. */
  26989. Scene.prototype.getGeometryByID = function (id) {
  26990. for (var index = 0; index < this.geometries.length; index++) {
  26991. if (this.geometries[index].id === id) {
  26992. return this.geometries[index];
  26993. }
  26994. }
  26995. return null;
  26996. };
  26997. /**
  26998. * Add a new geometry to this scene
  26999. * @param geometry defines the geometry to be added to the scene.
  27000. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27001. * @return a boolean defining if the geometry was added or not
  27002. */
  27003. Scene.prototype.pushGeometry = function (geometry, force) {
  27004. if (!force && this.getGeometryByID(geometry.id)) {
  27005. return false;
  27006. }
  27007. this.geometries.push(geometry);
  27008. //notify the collision coordinator
  27009. if (this.collisionCoordinator) {
  27010. this.collisionCoordinator.onGeometryAdded(geometry);
  27011. }
  27012. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27013. return true;
  27014. };
  27015. /**
  27016. * Removes an existing geometry
  27017. * @param geometry defines the geometry to be removed from the scene
  27018. * @return a boolean defining if the geometry was removed or not
  27019. */
  27020. Scene.prototype.removeGeometry = function (geometry) {
  27021. var index = this.geometries.indexOf(geometry);
  27022. if (index > -1) {
  27023. this.geometries.splice(index, 1);
  27024. //notify the collision coordinator
  27025. if (this.collisionCoordinator) {
  27026. this.collisionCoordinator.onGeometryDeleted(geometry);
  27027. }
  27028. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27029. return true;
  27030. }
  27031. return false;
  27032. };
  27033. /**
  27034. * Gets the list of geometries attached to the scene
  27035. * @returns an array of Geometry
  27036. */
  27037. Scene.prototype.getGeometries = function () {
  27038. return this.geometries;
  27039. };
  27040. /**
  27041. * Gets the first added mesh found of a given ID
  27042. * @param id defines the id to search for
  27043. * @return the mesh found or null if not found at all
  27044. */
  27045. Scene.prototype.getMeshByID = function (id) {
  27046. for (var index = 0; index < this.meshes.length; index++) {
  27047. if (this.meshes[index].id === id) {
  27048. return this.meshes[index];
  27049. }
  27050. }
  27051. return null;
  27052. };
  27053. /**
  27054. * Gets a list of meshes using their id
  27055. * @param id defines the id to search for
  27056. * @returns a list of meshes
  27057. */
  27058. Scene.prototype.getMeshesByID = function (id) {
  27059. return this.meshes.filter(function (m) {
  27060. return m.id === id;
  27061. });
  27062. };
  27063. /**
  27064. * Gets the first added transform node found of a given ID
  27065. * @param id defines the id to search for
  27066. * @return the found transform node or null if not found at all.
  27067. */
  27068. Scene.prototype.getTransformNodeByID = function (id) {
  27069. for (var index = 0; index < this.transformNodes.length; index++) {
  27070. if (this.transformNodes[index].id === id) {
  27071. return this.transformNodes[index];
  27072. }
  27073. }
  27074. return null;
  27075. };
  27076. /**
  27077. * Gets a list of transform nodes using their id
  27078. * @param id defines the id to search for
  27079. * @returns a list of transform nodes
  27080. */
  27081. Scene.prototype.getTransformNodesByID = function (id) {
  27082. return this.transformNodes.filter(function (m) {
  27083. return m.id === id;
  27084. });
  27085. };
  27086. /**
  27087. * Gets a mesh with its auto-generated unique id
  27088. * @param uniqueId defines the unique id to search for
  27089. * @return the found mesh or null if not found at all.
  27090. */
  27091. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27092. for (var index = 0; index < this.meshes.length; index++) {
  27093. if (this.meshes[index].uniqueId === uniqueId) {
  27094. return this.meshes[index];
  27095. }
  27096. }
  27097. return null;
  27098. };
  27099. /**
  27100. * Gets a the last added mesh using a given id
  27101. * @param id defines the id to search for
  27102. * @return the found mesh or null if not found at all.
  27103. */
  27104. Scene.prototype.getLastMeshByID = function (id) {
  27105. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27106. if (this.meshes[index].id === id) {
  27107. return this.meshes[index];
  27108. }
  27109. }
  27110. return null;
  27111. };
  27112. /**
  27113. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27114. * @param id defines the id to search for
  27115. * @return the found node or null if not found at all
  27116. */
  27117. Scene.prototype.getLastEntryByID = function (id) {
  27118. var index;
  27119. for (index = this.meshes.length - 1; index >= 0; index--) {
  27120. if (this.meshes[index].id === id) {
  27121. return this.meshes[index];
  27122. }
  27123. }
  27124. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27125. if (this.transformNodes[index].id === id) {
  27126. return this.transformNodes[index];
  27127. }
  27128. }
  27129. for (index = this.cameras.length - 1; index >= 0; index--) {
  27130. if (this.cameras[index].id === id) {
  27131. return this.cameras[index];
  27132. }
  27133. }
  27134. for (index = this.lights.length - 1; index >= 0; index--) {
  27135. if (this.lights[index].id === id) {
  27136. return this.lights[index];
  27137. }
  27138. }
  27139. return null;
  27140. };
  27141. /**
  27142. * Gets a node (Mesh, Camera, Light) using a given id
  27143. * @param id defines the id to search for
  27144. * @return the found node or null if not found at all
  27145. */
  27146. Scene.prototype.getNodeByID = function (id) {
  27147. var mesh = this.getMeshByID(id);
  27148. if (mesh) {
  27149. return mesh;
  27150. }
  27151. var light = this.getLightByID(id);
  27152. if (light) {
  27153. return light;
  27154. }
  27155. var camera = this.getCameraByID(id);
  27156. if (camera) {
  27157. return camera;
  27158. }
  27159. var bone = this.getBoneByID(id);
  27160. return bone;
  27161. };
  27162. /**
  27163. * Gets a node (Mesh, Camera, Light) using a given name
  27164. * @param name defines the name to search for
  27165. * @return the found node or null if not found at all.
  27166. */
  27167. Scene.prototype.getNodeByName = function (name) {
  27168. var mesh = this.getMeshByName(name);
  27169. if (mesh) {
  27170. return mesh;
  27171. }
  27172. var light = this.getLightByName(name);
  27173. if (light) {
  27174. return light;
  27175. }
  27176. var camera = this.getCameraByName(name);
  27177. if (camera) {
  27178. return camera;
  27179. }
  27180. var bone = this.getBoneByName(name);
  27181. return bone;
  27182. };
  27183. /**
  27184. * Gets a mesh using a given name
  27185. * @param name defines the name to search for
  27186. * @return the found mesh or null if not found at all.
  27187. */
  27188. Scene.prototype.getMeshByName = function (name) {
  27189. for (var index = 0; index < this.meshes.length; index++) {
  27190. if (this.meshes[index].name === name) {
  27191. return this.meshes[index];
  27192. }
  27193. }
  27194. return null;
  27195. };
  27196. /**
  27197. * Gets a transform node using a given name
  27198. * @param name defines the name to search for
  27199. * @return the found transform node or null if not found at all.
  27200. */
  27201. Scene.prototype.getTransformNodeByName = function (name) {
  27202. for (var index = 0; index < this.transformNodes.length; index++) {
  27203. if (this.transformNodes[index].name === name) {
  27204. return this.transformNodes[index];
  27205. }
  27206. }
  27207. return null;
  27208. };
  27209. /**
  27210. * Gets a sound using a given name
  27211. * @param name defines the name to search for
  27212. * @return the found sound or null if not found at all.
  27213. */
  27214. Scene.prototype.getSoundByName = function (name) {
  27215. var index;
  27216. if (BABYLON.AudioEngine) {
  27217. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27218. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27219. return this.mainSoundTrack.soundCollection[index];
  27220. }
  27221. }
  27222. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27223. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27224. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27225. return this.soundTracks[sdIndex].soundCollection[index];
  27226. }
  27227. }
  27228. }
  27229. }
  27230. return null;
  27231. };
  27232. /**
  27233. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27234. * @param id defines the id to search for
  27235. * @return the found skeleton or null if not found at all.
  27236. */
  27237. Scene.prototype.getLastSkeletonByID = function (id) {
  27238. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27239. if (this.skeletons[index].id === id) {
  27240. return this.skeletons[index];
  27241. }
  27242. }
  27243. return null;
  27244. };
  27245. /**
  27246. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27247. * @param id defines the id to search for
  27248. * @return the found skeleton or null if not found at all.
  27249. */
  27250. Scene.prototype.getSkeletonById = function (id) {
  27251. for (var index = 0; index < this.skeletons.length; index++) {
  27252. if (this.skeletons[index].id === id) {
  27253. return this.skeletons[index];
  27254. }
  27255. }
  27256. return null;
  27257. };
  27258. /**
  27259. * Gets a skeleton using a given name
  27260. * @param name defines the name to search for
  27261. * @return the found skeleton or null if not found at all.
  27262. */
  27263. Scene.prototype.getSkeletonByName = function (name) {
  27264. for (var index = 0; index < this.skeletons.length; index++) {
  27265. if (this.skeletons[index].name === name) {
  27266. return this.skeletons[index];
  27267. }
  27268. }
  27269. return null;
  27270. };
  27271. /**
  27272. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27273. * @param id defines the id to search for
  27274. * @return the found morph target manager or null if not found at all.
  27275. */
  27276. Scene.prototype.getMorphTargetManagerById = function (id) {
  27277. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27278. if (this.morphTargetManagers[index].uniqueId === id) {
  27279. return this.morphTargetManagers[index];
  27280. }
  27281. }
  27282. return null;
  27283. };
  27284. /**
  27285. * Gets a boolean indicating if the given mesh is active
  27286. * @param mesh defines the mesh to look for
  27287. * @returns true if the mesh is in the active list
  27288. */
  27289. Scene.prototype.isActiveMesh = function (mesh) {
  27290. return (this._activeMeshes.indexOf(mesh) !== -1);
  27291. };
  27292. Object.defineProperty(Scene.prototype, "uid", {
  27293. /**
  27294. * Return a unique id as a string which can serve as an identifier for the scene
  27295. */
  27296. get: function () {
  27297. if (!this._uid) {
  27298. this._uid = BABYLON.Tools.RandomId();
  27299. }
  27300. return this._uid;
  27301. },
  27302. enumerable: true,
  27303. configurable: true
  27304. });
  27305. /**
  27306. * Add an externaly attached data from its key.
  27307. * This method call will fail and return false, if such key already exists.
  27308. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27309. * @param key the unique key that identifies the data
  27310. * @param data the data object to associate to the key for this Engine instance
  27311. * @return true if no such key were already present and the data was added successfully, false otherwise
  27312. */
  27313. Scene.prototype.addExternalData = function (key, data) {
  27314. if (!this._externalData) {
  27315. this._externalData = new BABYLON.StringDictionary();
  27316. }
  27317. return this._externalData.add(key, data);
  27318. };
  27319. /**
  27320. * Get an externaly attached data from its key
  27321. * @param key the unique key that identifies the data
  27322. * @return the associated data, if present (can be null), or undefined if not present
  27323. */
  27324. Scene.prototype.getExternalData = function (key) {
  27325. if (!this._externalData) {
  27326. return null;
  27327. }
  27328. return this._externalData.get(key);
  27329. };
  27330. /**
  27331. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27332. * @param key the unique key that identifies the data
  27333. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27334. * @return the associated data, can be null if the factory returned null.
  27335. */
  27336. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27337. if (!this._externalData) {
  27338. this._externalData = new BABYLON.StringDictionary();
  27339. }
  27340. return this._externalData.getOrAddWithFactory(key, factory);
  27341. };
  27342. /**
  27343. * Remove an externaly attached data from the Engine instance
  27344. * @param key the unique key that identifies the data
  27345. * @return true if the data was successfully removed, false if it doesn't exist
  27346. */
  27347. Scene.prototype.removeExternalData = function (key) {
  27348. return this._externalData.remove(key);
  27349. };
  27350. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27351. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27352. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27353. var step = _a[_i];
  27354. step.action(mesh, subMesh);
  27355. }
  27356. var material = subMesh.getMaterial();
  27357. if (material !== null && material !== undefined) {
  27358. // Render targets
  27359. if (material.getRenderTargetTextures !== undefined) {
  27360. if (this._processedMaterials.indexOf(material) === -1) {
  27361. this._processedMaterials.push(material);
  27362. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27363. }
  27364. }
  27365. // Dispatch
  27366. this._activeIndices.addCount(subMesh.indexCount, false);
  27367. this._renderingManager.dispatch(subMesh, mesh, material);
  27368. }
  27369. }
  27370. };
  27371. /**
  27372. * Clear the processed materials smart array preventing retention point in material dispose.
  27373. */
  27374. Scene.prototype.freeProcessedMaterials = function () {
  27375. this._processedMaterials.dispose();
  27376. };
  27377. /**
  27378. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27379. */
  27380. Scene.prototype.freeActiveMeshes = function () {
  27381. this._activeMeshes.dispose();
  27382. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27383. this.activeCamera._activeMeshes.dispose();
  27384. }
  27385. if (this.activeCameras) {
  27386. for (var i = 0; i < this.activeCameras.length; i++) {
  27387. var activeCamera = this.activeCameras[i];
  27388. if (activeCamera && activeCamera._activeMeshes) {
  27389. activeCamera._activeMeshes.dispose();
  27390. }
  27391. }
  27392. }
  27393. };
  27394. /**
  27395. * Clear the info related to rendering groups preventing retention points during dispose.
  27396. */
  27397. Scene.prototype.freeRenderingGroups = function () {
  27398. if (this._renderingManager) {
  27399. this._renderingManager.freeRenderingGroups();
  27400. }
  27401. if (this.textures) {
  27402. for (var i = 0; i < this.textures.length; i++) {
  27403. var texture = this.textures[i];
  27404. if (texture && texture.renderList) {
  27405. texture.freeRenderingGroups();
  27406. }
  27407. }
  27408. }
  27409. };
  27410. /** @hidden */
  27411. Scene.prototype._isInIntermediateRendering = function () {
  27412. return this._intermediateRendering;
  27413. };
  27414. /**
  27415. * Defines the current active mesh candidate provider
  27416. * @param provider defines the provider to use
  27417. */
  27418. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27419. this._activeMeshCandidateProvider = provider;
  27420. };
  27421. /**
  27422. * Gets the current active mesh candidate provider
  27423. * @returns the current active mesh candidate provider
  27424. */
  27425. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27426. return this._activeMeshCandidateProvider;
  27427. };
  27428. /**
  27429. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27430. * @returns the current scene
  27431. */
  27432. Scene.prototype.freezeActiveMeshes = function () {
  27433. if (!this.activeCamera) {
  27434. return this;
  27435. }
  27436. if (!this._frustumPlanes) {
  27437. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27438. }
  27439. this._evaluateActiveMeshes();
  27440. this._activeMeshesFrozen = true;
  27441. return this;
  27442. };
  27443. /**
  27444. * Use this function to restart evaluating active meshes on every frame
  27445. * @returns the current scene
  27446. */
  27447. Scene.prototype.unfreezeActiveMeshes = function () {
  27448. this._activeMeshesFrozen = false;
  27449. return this;
  27450. };
  27451. Scene.prototype._evaluateActiveMeshes = function () {
  27452. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27453. return;
  27454. }
  27455. if (!this.activeCamera) {
  27456. return;
  27457. }
  27458. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27459. this.activeCamera._activeMeshes.reset();
  27460. this._activeMeshes.reset();
  27461. this._renderingManager.reset();
  27462. this._processedMaterials.reset();
  27463. this._activeParticleSystems.reset();
  27464. this._activeSkeletons.reset();
  27465. this._softwareSkinnedMeshes.reset();
  27466. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27467. var step = _a[_i];
  27468. step.action();
  27469. }
  27470. // Meshes
  27471. var meshes;
  27472. var len;
  27473. var checkIsEnabled = true;
  27474. // Determine mesh candidates
  27475. if (this._activeMeshCandidateProvider !== undefined) {
  27476. // Use _activeMeshCandidateProvider
  27477. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27478. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27479. if (meshes !== undefined) {
  27480. len = meshes.length;
  27481. }
  27482. else {
  27483. len = 0;
  27484. }
  27485. }
  27486. else if (this._selectionOctree !== undefined) {
  27487. // Octree
  27488. var selection = this._selectionOctree.select(this._frustumPlanes);
  27489. meshes = selection.data;
  27490. len = selection.length;
  27491. }
  27492. else {
  27493. // Full scene traversal
  27494. len = this.meshes.length;
  27495. meshes = this.meshes;
  27496. }
  27497. // Check each mesh
  27498. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27499. mesh = meshes[meshIndex];
  27500. if (mesh.isBlocked) {
  27501. continue;
  27502. }
  27503. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27504. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27505. continue;
  27506. }
  27507. mesh.computeWorldMatrix();
  27508. // Intersections
  27509. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  27510. this._meshesForIntersections.pushNoDuplicate(mesh);
  27511. }
  27512. // Switch to current LOD
  27513. meshLOD = mesh.getLOD(this.activeCamera);
  27514. if (meshLOD === undefined || meshLOD === null) {
  27515. continue;
  27516. }
  27517. mesh._preActivate();
  27518. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27519. this._activeMeshes.push(mesh);
  27520. this.activeCamera._activeMeshes.push(mesh);
  27521. mesh._activate(this._renderId);
  27522. if (meshLOD !== mesh) {
  27523. meshLOD._activate(this._renderId);
  27524. }
  27525. this._activeMesh(mesh, meshLOD);
  27526. }
  27527. }
  27528. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27529. // Particle systems
  27530. if (this.particlesEnabled) {
  27531. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27532. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27533. var particleSystem = this.particleSystems[particleIndex];
  27534. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27535. continue;
  27536. }
  27537. var emitter = particleSystem.emitter;
  27538. if (!emitter.position || emitter.isEnabled()) {
  27539. this._activeParticleSystems.push(particleSystem);
  27540. particleSystem.animate();
  27541. this._renderingManager.dispatchParticles(particleSystem);
  27542. }
  27543. }
  27544. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27545. }
  27546. };
  27547. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27548. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27549. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27550. mesh.skeleton.prepare();
  27551. }
  27552. if (!mesh.computeBonesUsingShaders) {
  27553. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27554. }
  27555. }
  27556. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27557. var step = _a[_i];
  27558. step.action(sourceMesh, mesh);
  27559. }
  27560. if (mesh !== undefined && mesh !== null
  27561. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27562. // Submeshes Octrees
  27563. var len;
  27564. var subMeshes;
  27565. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27566. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27567. len = intersections.length;
  27568. subMeshes = intersections.data;
  27569. }
  27570. else {
  27571. subMeshes = mesh.subMeshes;
  27572. len = subMeshes.length;
  27573. }
  27574. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27575. subMesh = subMeshes[subIndex];
  27576. this._evaluateSubMesh(subMesh, mesh);
  27577. }
  27578. }
  27579. };
  27580. /**
  27581. * Update the transform matrix to update from the current active camera
  27582. * @param force defines a boolean used to force the update even if cache is up to date
  27583. */
  27584. Scene.prototype.updateTransformMatrix = function (force) {
  27585. if (!this.activeCamera) {
  27586. return;
  27587. }
  27588. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27589. };
  27590. /**
  27591. * 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)
  27592. * @param alternateCamera defines the camera to use
  27593. */
  27594. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27595. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27596. };
  27597. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27598. if (camera && camera._skipRendering) {
  27599. return;
  27600. }
  27601. var engine = this._engine;
  27602. this.activeCamera = camera;
  27603. if (!this.activeCamera)
  27604. throw new Error("Active camera not set");
  27605. // Viewport
  27606. engine.setViewport(this.activeCamera.viewport);
  27607. // Camera
  27608. this.resetCachedMaterial();
  27609. this._renderId++;
  27610. this.updateTransformMatrix();
  27611. if (camera._alternateCamera) {
  27612. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27613. this._alternateRendering = true;
  27614. }
  27615. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27616. // Meshes
  27617. this._evaluateActiveMeshes();
  27618. // Software skinning
  27619. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27620. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27621. mesh.applySkeleton(mesh.skeleton);
  27622. }
  27623. // Render targets
  27624. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27625. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27626. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27627. }
  27628. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27629. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27630. }
  27631. if (this.renderTargetsEnabled) {
  27632. this._intermediateRendering = true;
  27633. if (this._renderTargets.length > 0) {
  27634. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27635. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27636. var renderTarget = this._renderTargets.data[renderIndex];
  27637. if (renderTarget._shouldRender()) {
  27638. this._renderId++;
  27639. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27640. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27641. }
  27642. }
  27643. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27644. this._renderId++;
  27645. }
  27646. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27647. var step = _a[_i];
  27648. step.action(this.activeCamera);
  27649. }
  27650. this._intermediateRendering = false;
  27651. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27652. }
  27653. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27654. // Prepare Frame
  27655. if (this.postProcessManager) {
  27656. this.postProcessManager._prepareFrame();
  27657. }
  27658. // Before Camera Draw
  27659. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27660. var step = _c[_b];
  27661. step.action(this.activeCamera);
  27662. }
  27663. // Render
  27664. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27665. this._renderingManager.render(null, null, true, true);
  27666. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27667. // After Camera Draw
  27668. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27669. var step = _e[_d];
  27670. step.action(this.activeCamera);
  27671. }
  27672. // Finalize frame
  27673. if (this.postProcessManager) {
  27674. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27675. }
  27676. // Reset some special arrays
  27677. this._renderTargets.reset();
  27678. this._alternateRendering = false;
  27679. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27680. };
  27681. Scene.prototype._processSubCameras = function (camera) {
  27682. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27683. this._renderForCamera(camera);
  27684. return;
  27685. }
  27686. // rig cameras
  27687. for (var index = 0; index < camera._rigCameras.length; index++) {
  27688. this._renderForCamera(camera._rigCameras[index], camera);
  27689. }
  27690. this.activeCamera = camera;
  27691. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27692. };
  27693. Scene.prototype._checkIntersections = function () {
  27694. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27695. var sourceMesh = this._meshesForIntersections.data[index];
  27696. if (!sourceMesh.actionManager) {
  27697. continue;
  27698. }
  27699. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27700. var action = sourceMesh.actionManager.actions[actionIndex];
  27701. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27702. var parameters = action.getTriggerParameter();
  27703. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27704. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27705. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27706. if (areIntersecting && currentIntersectionInProgress === -1) {
  27707. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27708. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27709. sourceMesh._intersectionsInProgress.push(otherMesh);
  27710. }
  27711. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27712. sourceMesh._intersectionsInProgress.push(otherMesh);
  27713. }
  27714. }
  27715. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27716. //They intersected, and now they don't.
  27717. //is this trigger an exit trigger? execute an event.
  27718. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27719. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27720. }
  27721. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27722. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27723. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27724. return otherMesh === parameterMesh;
  27725. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27726. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27727. }
  27728. }
  27729. }
  27730. }
  27731. }
  27732. };
  27733. /**
  27734. * Render the scene
  27735. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27736. */
  27737. Scene.prototype.render = function (updateCameras) {
  27738. if (updateCameras === void 0) { updateCameras = true; }
  27739. if (this.isDisposed) {
  27740. return;
  27741. }
  27742. // Register components that have been associated lately to the scene.
  27743. this._registerTransientComponents();
  27744. this._activeParticles.fetchNewFrame();
  27745. this._totalVertices.fetchNewFrame();
  27746. this._activeIndices.fetchNewFrame();
  27747. this._activeBones.fetchNewFrame();
  27748. this._meshesForIntersections.reset();
  27749. this.resetCachedMaterial();
  27750. this.onBeforeAnimationsObservable.notifyObservers(this);
  27751. // Actions
  27752. if (this.actionManager) {
  27753. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27754. }
  27755. if (this._engine.isDeterministicLockStep()) {
  27756. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27757. var defaultFPS = (60.0 / 1000.0);
  27758. var defaultFrameTime = 1000 / 60; // frame time in MS
  27759. if (this._physicsEngine) {
  27760. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27761. }
  27762. var stepsTaken = 0;
  27763. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27764. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27765. internalSteps = Math.min(internalSteps, maxSubSteps);
  27766. do {
  27767. this.onBeforeStepObservable.notifyObservers(this);
  27768. // Animations
  27769. this._animationRatio = defaultFrameTime * defaultFPS;
  27770. this._animate();
  27771. this.onAfterAnimationsObservable.notifyObservers(this);
  27772. // Physics
  27773. if (this._physicsEngine) {
  27774. this.onBeforePhysicsObservable.notifyObservers(this);
  27775. this._physicsEngine._step(defaultFrameTime / 1000);
  27776. this.onAfterPhysicsObservable.notifyObservers(this);
  27777. }
  27778. this.onAfterStepObservable.notifyObservers(this);
  27779. this._currentStepId++;
  27780. stepsTaken++;
  27781. deltaTime -= defaultFrameTime;
  27782. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27783. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27784. }
  27785. else {
  27786. // Animations
  27787. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27788. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27789. this._animate();
  27790. this.onAfterAnimationsObservable.notifyObservers(this);
  27791. // Physics
  27792. if (this._physicsEngine) {
  27793. this.onBeforePhysicsObservable.notifyObservers(this);
  27794. this._physicsEngine._step(deltaTime / 1000.0);
  27795. this.onAfterPhysicsObservable.notifyObservers(this);
  27796. }
  27797. }
  27798. // Before camera update steps
  27799. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27800. var step = _a[_i];
  27801. step.action();
  27802. }
  27803. // Update Cameras
  27804. if (updateCameras) {
  27805. if (this.activeCameras.length > 0) {
  27806. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27807. var camera = this.activeCameras[cameraIndex];
  27808. camera.update();
  27809. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27810. // rig cameras
  27811. for (var index = 0; index < camera._rigCameras.length; index++) {
  27812. camera._rigCameras[index].update();
  27813. }
  27814. }
  27815. }
  27816. }
  27817. else if (this.activeCamera) {
  27818. this.activeCamera.update();
  27819. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27820. // rig cameras
  27821. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27822. this.activeCamera._rigCameras[index].update();
  27823. }
  27824. }
  27825. }
  27826. }
  27827. // Before render
  27828. this.onBeforeRenderObservable.notifyObservers(this);
  27829. // Customs render targets
  27830. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27831. var engine = this.getEngine();
  27832. var currentActiveCamera = this.activeCamera;
  27833. if (this.renderTargetsEnabled) {
  27834. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27835. this._intermediateRendering = true;
  27836. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27837. var renderTarget = this.customRenderTargets[customIndex];
  27838. if (renderTarget._shouldRender()) {
  27839. this._renderId++;
  27840. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27841. if (!this.activeCamera)
  27842. throw new Error("Active camera not set");
  27843. // Viewport
  27844. engine.setViewport(this.activeCamera.viewport);
  27845. // Camera
  27846. this.updateTransformMatrix();
  27847. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27848. }
  27849. }
  27850. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27851. this._intermediateRendering = false;
  27852. this._renderId++;
  27853. }
  27854. // Restore back buffer
  27855. if (this.customRenderTargets.length > 0) {
  27856. engine.restoreDefaultFramebuffer();
  27857. }
  27858. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27859. this.activeCamera = currentActiveCamera;
  27860. // Procedural textures
  27861. if (this.proceduralTexturesEnabled) {
  27862. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27863. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27864. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27865. if (proceduralTexture._shouldRender()) {
  27866. proceduralTexture.render();
  27867. }
  27868. }
  27869. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27870. }
  27871. // Clear
  27872. if (this.autoClearDepthAndStencil || this.autoClear) {
  27873. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27874. }
  27875. // Shadows
  27876. if (this.shadowsEnabled) {
  27877. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27878. var light = this.lights[lightIndex];
  27879. var shadowGenerator = light.getShadowGenerator();
  27880. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27881. var shadowMap = (shadowGenerator.getShadowMap());
  27882. if (this.textures.indexOf(shadowMap) !== -1) {
  27883. this._renderTargets.push(shadowMap);
  27884. }
  27885. }
  27886. }
  27887. }
  27888. // Collects render targets from external components.
  27889. for (var _b = 0, _c = this._gatherRenderTargetsStage; _b < _c.length; _b++) {
  27890. var step = _c[_b];
  27891. step.action(this._renderTargets);
  27892. }
  27893. // Multi-cameras?
  27894. if (this.activeCameras.length > 0) {
  27895. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27896. if (cameraIndex > 0) {
  27897. this._engine.clear(null, false, true, true);
  27898. }
  27899. this._processSubCameras(this.activeCameras[cameraIndex]);
  27900. }
  27901. }
  27902. else {
  27903. if (!this.activeCamera) {
  27904. throw new Error("No camera defined");
  27905. }
  27906. this._processSubCameras(this.activeCamera);
  27907. }
  27908. // Intersection checks
  27909. this._checkIntersections();
  27910. // Update the audio listener attached to the camera
  27911. if (BABYLON.AudioEngine) {
  27912. this._updateAudioParameters();
  27913. }
  27914. // After render
  27915. if (this.afterRender) {
  27916. this.afterRender();
  27917. }
  27918. this.onAfterRenderObservable.notifyObservers(this);
  27919. // Cleaning
  27920. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27921. var data = this._toBeDisposed.data[index];
  27922. if (data) {
  27923. data.dispose();
  27924. }
  27925. this._toBeDisposed[index] = null;
  27926. }
  27927. this._toBeDisposed.reset();
  27928. if (this.dumpNextRenderTargets) {
  27929. this.dumpNextRenderTargets = false;
  27930. }
  27931. this._activeBones.addCount(0, true);
  27932. this._activeIndices.addCount(0, true);
  27933. this._activeParticles.addCount(0, true);
  27934. };
  27935. Scene.prototype._updateAudioParameters = function () {
  27936. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27937. return;
  27938. }
  27939. var listeningCamera;
  27940. var audioEngine = BABYLON.Engine.audioEngine;
  27941. if (this.activeCameras.length > 0) {
  27942. listeningCamera = this.activeCameras[0];
  27943. }
  27944. else {
  27945. listeningCamera = this.activeCamera;
  27946. }
  27947. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27948. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27949. // for VR cameras
  27950. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27951. listeningCamera = listeningCamera.rigCameras[0];
  27952. }
  27953. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27954. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27955. cameraDirection.normalize();
  27956. // To avoid some errors on GearVR
  27957. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27958. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27959. }
  27960. var i;
  27961. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27962. var sound = this.mainSoundTrack.soundCollection[i];
  27963. if (sound.useCustomAttenuation) {
  27964. sound.updateDistanceFromListener();
  27965. }
  27966. }
  27967. for (i = 0; i < this.soundTracks.length; i++) {
  27968. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27969. sound = this.soundTracks[i].soundCollection[j];
  27970. if (sound.useCustomAttenuation) {
  27971. sound.updateDistanceFromListener();
  27972. }
  27973. }
  27974. }
  27975. }
  27976. };
  27977. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27978. // Audio
  27979. /**
  27980. * Gets or sets if audio support is enabled
  27981. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27982. */
  27983. get: function () {
  27984. return this._audioEnabled;
  27985. },
  27986. set: function (value) {
  27987. this._audioEnabled = value;
  27988. if (BABYLON.AudioEngine) {
  27989. if (this._audioEnabled) {
  27990. this._enableAudio();
  27991. }
  27992. else {
  27993. this._disableAudio();
  27994. }
  27995. }
  27996. },
  27997. enumerable: true,
  27998. configurable: true
  27999. });
  28000. Scene.prototype._disableAudio = function () {
  28001. var i;
  28002. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28003. this.mainSoundTrack.soundCollection[i].pause();
  28004. }
  28005. for (i = 0; i < this.soundTracks.length; i++) {
  28006. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28007. this.soundTracks[i].soundCollection[j].pause();
  28008. }
  28009. }
  28010. };
  28011. Scene.prototype._enableAudio = function () {
  28012. var i;
  28013. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28014. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28015. this.mainSoundTrack.soundCollection[i].play();
  28016. }
  28017. }
  28018. for (i = 0; i < this.soundTracks.length; i++) {
  28019. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28020. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28021. this.soundTracks[i].soundCollection[j].play();
  28022. }
  28023. }
  28024. }
  28025. };
  28026. Object.defineProperty(Scene.prototype, "headphone", {
  28027. /**
  28028. * Gets or sets if audio will be output to headphones
  28029. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28030. */
  28031. get: function () {
  28032. return this._headphone;
  28033. },
  28034. set: function (value) {
  28035. this._headphone = value;
  28036. if (BABYLON.AudioEngine) {
  28037. if (this._headphone) {
  28038. this._switchAudioModeForHeadphones();
  28039. }
  28040. else {
  28041. this._switchAudioModeForNormalSpeakers();
  28042. }
  28043. }
  28044. },
  28045. enumerable: true,
  28046. configurable: true
  28047. });
  28048. Scene.prototype._switchAudioModeForHeadphones = function () {
  28049. this.mainSoundTrack.switchPanningModelToHRTF();
  28050. for (var i = 0; i < this.soundTracks.length; i++) {
  28051. this.soundTracks[i].switchPanningModelToHRTF();
  28052. }
  28053. };
  28054. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28055. this.mainSoundTrack.switchPanningModelToEqualPower();
  28056. for (var i = 0; i < this.soundTracks.length; i++) {
  28057. this.soundTracks[i].switchPanningModelToEqualPower();
  28058. }
  28059. };
  28060. /**
  28061. * Freeze all materials
  28062. * A frozen material will not be updatable but should be faster to render
  28063. */
  28064. Scene.prototype.freezeMaterials = function () {
  28065. for (var i = 0; i < this.materials.length; i++) {
  28066. this.materials[i].freeze();
  28067. }
  28068. };
  28069. /**
  28070. * Unfreeze all materials
  28071. * A frozen material will not be updatable but should be faster to render
  28072. */
  28073. Scene.prototype.unfreezeMaterials = function () {
  28074. for (var i = 0; i < this.materials.length; i++) {
  28075. this.materials[i].unfreeze();
  28076. }
  28077. };
  28078. /**
  28079. * Releases all held ressources
  28080. */
  28081. Scene.prototype.dispose = function () {
  28082. this.beforeRender = null;
  28083. this.afterRender = null;
  28084. this.skeletons = [];
  28085. this.morphTargetManagers = [];
  28086. this._transientComponents = [];
  28087. this._isReadyForMeshStage.clear();
  28088. this._beforeEvaluateActiveMeshStage.clear();
  28089. this._evaluateSubMeshStage.clear();
  28090. this._activeMeshStage.clear();
  28091. this._cameraDrawRenderTargetStage.clear();
  28092. this._beforeCameraDrawStage.clear();
  28093. this._beforeRenderingGroupDrawStage.clear();
  28094. this._afterRenderingGroupDrawStage.clear();
  28095. this._afterCameraDrawStage.clear();
  28096. this._beforeCameraUpdateStage.clear();
  28097. this._gatherRenderTargetsStage.clear();
  28098. this._rebuildGeometryStage.clear();
  28099. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28100. var component = _a[_i];
  28101. component.dispose();
  28102. }
  28103. this.importedMeshesFiles = new Array();
  28104. this.stopAllAnimations();
  28105. this.resetCachedMaterial();
  28106. // Smart arrays
  28107. if (this.activeCamera) {
  28108. this.activeCamera._activeMeshes.dispose();
  28109. this.activeCamera = null;
  28110. }
  28111. this._activeMeshes.dispose();
  28112. this._renderingManager.dispose();
  28113. this._processedMaterials.dispose();
  28114. this._activeParticleSystems.dispose();
  28115. this._activeSkeletons.dispose();
  28116. this._softwareSkinnedMeshes.dispose();
  28117. this._renderTargets.dispose();
  28118. this._registeredForLateAnimationBindings.dispose();
  28119. this._meshesForIntersections.dispose();
  28120. this._toBeDisposed.dispose();
  28121. // Abort active requests
  28122. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28123. var request = _c[_b];
  28124. request.abort();
  28125. }
  28126. // Debug layer
  28127. if (this._debugLayer) {
  28128. this._debugLayer.hide();
  28129. }
  28130. // Events
  28131. this.onDisposeObservable.notifyObservers(this);
  28132. this.onDisposeObservable.clear();
  28133. this.onBeforeRenderObservable.clear();
  28134. this.onAfterRenderObservable.clear();
  28135. this.onBeforeRenderTargetsRenderObservable.clear();
  28136. this.onAfterRenderTargetsRenderObservable.clear();
  28137. this.onAfterStepObservable.clear();
  28138. this.onBeforeStepObservable.clear();
  28139. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28140. this.onAfterActiveMeshesEvaluationObservable.clear();
  28141. this.onBeforeParticlesRenderingObservable.clear();
  28142. this.onAfterParticlesRenderingObservable.clear();
  28143. this.onBeforeSpritesRenderingObservable.clear();
  28144. this.onAfterSpritesRenderingObservable.clear();
  28145. this.onBeforeDrawPhaseObservable.clear();
  28146. this.onAfterDrawPhaseObservable.clear();
  28147. this.onBeforePhysicsObservable.clear();
  28148. this.onAfterPhysicsObservable.clear();
  28149. this.onBeforeAnimationsObservable.clear();
  28150. this.onAfterAnimationsObservable.clear();
  28151. this.onDataLoadedObservable.clear();
  28152. this.onBeforeRenderingGroupObservable.clear();
  28153. this.onAfterRenderingGroupObservable.clear();
  28154. this.detachControl();
  28155. // Release sounds & sounds tracks
  28156. if (BABYLON.AudioEngine) {
  28157. this.disposeSounds();
  28158. }
  28159. // VR Helper
  28160. if (this.VRHelper) {
  28161. this.VRHelper.dispose();
  28162. }
  28163. // Detach cameras
  28164. var canvas = this._engine.getRenderingCanvas();
  28165. if (canvas) {
  28166. var index;
  28167. for (index = 0; index < this.cameras.length; index++) {
  28168. this.cameras[index].detachControl(canvas);
  28169. }
  28170. }
  28171. // Release animation groups
  28172. while (this.animationGroups.length) {
  28173. this.animationGroups[0].dispose();
  28174. }
  28175. // Release lights
  28176. while (this.lights.length) {
  28177. this.lights[0].dispose();
  28178. }
  28179. // Release meshes
  28180. while (this.meshes.length) {
  28181. this.meshes[0].dispose(true);
  28182. }
  28183. while (this.transformNodes.length) {
  28184. this.removeTransformNode(this.transformNodes[0]);
  28185. }
  28186. // Release cameras
  28187. while (this.cameras.length) {
  28188. this.cameras[0].dispose();
  28189. }
  28190. // Release materials
  28191. if (this.defaultMaterial) {
  28192. this.defaultMaterial.dispose();
  28193. }
  28194. while (this.multiMaterials.length) {
  28195. this.multiMaterials[0].dispose();
  28196. }
  28197. while (this.materials.length) {
  28198. this.materials[0].dispose();
  28199. }
  28200. // Release particles
  28201. while (this.particleSystems.length) {
  28202. this.particleSystems[0].dispose();
  28203. }
  28204. // Release sprites
  28205. while (this.spriteManagers.length) {
  28206. this.spriteManagers[0].dispose();
  28207. }
  28208. // Release postProcesses
  28209. while (this.postProcesses.length) {
  28210. this.postProcesses[0].dispose();
  28211. }
  28212. // Release textures
  28213. while (this.textures.length) {
  28214. this.textures[0].dispose();
  28215. }
  28216. // Release UBO
  28217. this._sceneUbo.dispose();
  28218. if (this._alternateSceneUbo) {
  28219. this._alternateSceneUbo.dispose();
  28220. }
  28221. // Post-processes
  28222. this.postProcessManager.dispose();
  28223. // Physics
  28224. if (this._physicsEngine) {
  28225. this.disablePhysicsEngine();
  28226. }
  28227. // Remove from engine
  28228. index = this._engine.scenes.indexOf(this);
  28229. if (index > -1) {
  28230. this._engine.scenes.splice(index, 1);
  28231. }
  28232. this._engine.wipeCaches(true);
  28233. this._isDisposed = true;
  28234. };
  28235. Object.defineProperty(Scene.prototype, "isDisposed", {
  28236. /**
  28237. * Gets if the scene is already disposed
  28238. */
  28239. get: function () {
  28240. return this._isDisposed;
  28241. },
  28242. enumerable: true,
  28243. configurable: true
  28244. });
  28245. /**
  28246. * Releases sounds & soundtracks
  28247. */
  28248. Scene.prototype.disposeSounds = function () {
  28249. if (!this._mainSoundTrack) {
  28250. return;
  28251. }
  28252. this.mainSoundTrack.dispose();
  28253. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28254. this.soundTracks[scIndex].dispose();
  28255. }
  28256. };
  28257. /**
  28258. * Call this function to reduce memory footprint of the scene.
  28259. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28260. */
  28261. Scene.prototype.clearCachedVertexData = function () {
  28262. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28263. var mesh = this.meshes[meshIndex];
  28264. var geometry = mesh.geometry;
  28265. if (geometry) {
  28266. geometry._indices = [];
  28267. for (var vbName in geometry._vertexBuffers) {
  28268. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28269. continue;
  28270. }
  28271. geometry._vertexBuffers[vbName]._buffer._data = null;
  28272. }
  28273. }
  28274. }
  28275. };
  28276. /**
  28277. * This function will remove the local cached buffer data from texture.
  28278. * It will save memory but will prevent the texture from being rebuilt
  28279. */
  28280. Scene.prototype.cleanCachedTextureBuffer = function () {
  28281. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28282. var baseTexture = _a[_i];
  28283. var buffer = baseTexture._buffer;
  28284. if (buffer) {
  28285. baseTexture._buffer = null;
  28286. }
  28287. }
  28288. };
  28289. // Octrees
  28290. /**
  28291. * Get the world extend vectors with an optional filter
  28292. *
  28293. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28294. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28295. */
  28296. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28297. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28298. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28299. filterPredicate = filterPredicate || (function () { return true; });
  28300. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28301. mesh.computeWorldMatrix(true);
  28302. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28303. return;
  28304. }
  28305. var boundingInfo = mesh.getBoundingInfo();
  28306. var minBox = boundingInfo.boundingBox.minimumWorld;
  28307. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28308. BABYLON.Tools.CheckExtends(minBox, min, max);
  28309. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28310. });
  28311. return {
  28312. min: min,
  28313. max: max
  28314. };
  28315. };
  28316. /**
  28317. * Creates or updates the octree used to boost selection (picking)
  28318. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28319. * @param maxCapacity defines the maximum capacity per leaf
  28320. * @param maxDepth defines the maximum depth of the octree
  28321. * @returns an octree of AbstractMesh
  28322. */
  28323. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28324. if (maxCapacity === void 0) { maxCapacity = 64; }
  28325. if (maxDepth === void 0) { maxDepth = 2; }
  28326. if (!this._selectionOctree) {
  28327. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28328. }
  28329. var worldExtends = this.getWorldExtends();
  28330. // Update octree
  28331. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28332. return this._selectionOctree;
  28333. };
  28334. // Picking
  28335. /**
  28336. * Creates a ray that can be used to pick in the scene
  28337. * @param x defines the x coordinate of the origin (on-screen)
  28338. * @param y defines the y coordinate of the origin (on-screen)
  28339. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28340. * @param camera defines the camera to use for the picking
  28341. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28342. * @returns a Ray
  28343. */
  28344. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28345. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28346. var result = BABYLON.Ray.Zero();
  28347. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28348. return result;
  28349. };
  28350. /**
  28351. * Creates a ray that can be used to pick in the scene
  28352. * @param x defines the x coordinate of the origin (on-screen)
  28353. * @param y defines the y coordinate of the origin (on-screen)
  28354. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28355. * @param result defines the ray where to store the picking ray
  28356. * @param camera defines the camera to use for the picking
  28357. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28358. * @returns the current scene
  28359. */
  28360. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28361. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28362. var engine = this._engine;
  28363. if (!camera) {
  28364. if (!this.activeCamera)
  28365. throw new Error("Active camera not set");
  28366. camera = this.activeCamera;
  28367. }
  28368. var cameraViewport = camera.viewport;
  28369. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28370. // Moving coordinates to local viewport world
  28371. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28372. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28373. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28374. return this;
  28375. };
  28376. /**
  28377. * Creates a ray that can be used to pick in the scene
  28378. * @param x defines the x coordinate of the origin (on-screen)
  28379. * @param y defines the y coordinate of the origin (on-screen)
  28380. * @param camera defines the camera to use for the picking
  28381. * @returns a Ray
  28382. */
  28383. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28384. var result = BABYLON.Ray.Zero();
  28385. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28386. return result;
  28387. };
  28388. /**
  28389. * Creates a ray that can be used to pick in the scene
  28390. * @param x defines the x coordinate of the origin (on-screen)
  28391. * @param y defines the y coordinate of the origin (on-screen)
  28392. * @param result defines the ray where to store the picking ray
  28393. * @param camera defines the camera to use for the picking
  28394. * @returns the current scene
  28395. */
  28396. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28397. if (!BABYLON.PickingInfo) {
  28398. return this;
  28399. }
  28400. var engine = this._engine;
  28401. if (!camera) {
  28402. if (!this.activeCamera)
  28403. throw new Error("Active camera not set");
  28404. camera = this.activeCamera;
  28405. }
  28406. var cameraViewport = camera.viewport;
  28407. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28408. var identity = BABYLON.Matrix.Identity();
  28409. // Moving coordinates to local viewport world
  28410. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28411. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28412. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28413. return this;
  28414. };
  28415. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28416. if (!BABYLON.PickingInfo) {
  28417. return null;
  28418. }
  28419. var pickingInfo = null;
  28420. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28421. var mesh = this.meshes[meshIndex];
  28422. if (predicate) {
  28423. if (!predicate(mesh)) {
  28424. continue;
  28425. }
  28426. }
  28427. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28428. continue;
  28429. }
  28430. var world = mesh.getWorldMatrix();
  28431. var ray = rayFunction(world);
  28432. var result = mesh.intersects(ray, fastCheck);
  28433. if (!result || !result.hit)
  28434. continue;
  28435. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28436. continue;
  28437. pickingInfo = result;
  28438. if (fastCheck) {
  28439. break;
  28440. }
  28441. }
  28442. return pickingInfo || new BABYLON.PickingInfo();
  28443. };
  28444. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28445. if (!BABYLON.PickingInfo) {
  28446. return null;
  28447. }
  28448. var pickingInfos = new Array();
  28449. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28450. var mesh = this.meshes[meshIndex];
  28451. if (predicate) {
  28452. if (!predicate(mesh)) {
  28453. continue;
  28454. }
  28455. }
  28456. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28457. continue;
  28458. }
  28459. var world = mesh.getWorldMatrix();
  28460. var ray = rayFunction(world);
  28461. var result = mesh.intersects(ray, false);
  28462. if (!result || !result.hit)
  28463. continue;
  28464. pickingInfos.push(result);
  28465. }
  28466. return pickingInfos;
  28467. };
  28468. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28469. if (!BABYLON.PickingInfo) {
  28470. return null;
  28471. }
  28472. var pickingInfo = null;
  28473. if (!camera) {
  28474. if (!this.activeCamera) {
  28475. return null;
  28476. }
  28477. camera = this.activeCamera;
  28478. }
  28479. if (this.spriteManagers.length > 0) {
  28480. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28481. var spriteManager = this.spriteManagers[spriteIndex];
  28482. if (!spriteManager.isPickable) {
  28483. continue;
  28484. }
  28485. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28486. if (!result || !result.hit)
  28487. continue;
  28488. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28489. continue;
  28490. pickingInfo = result;
  28491. if (fastCheck) {
  28492. break;
  28493. }
  28494. }
  28495. }
  28496. return pickingInfo || new BABYLON.PickingInfo();
  28497. };
  28498. /** Launch a ray to try to pick a mesh in the scene
  28499. * @param x position on screen
  28500. * @param y position on screen
  28501. * @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
  28502. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28503. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28504. * @returns a PickingInfo
  28505. */
  28506. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28507. var _this = this;
  28508. if (!BABYLON.PickingInfo) {
  28509. return null;
  28510. }
  28511. var result = this._internalPick(function (world) {
  28512. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28513. return _this._tempPickingRay;
  28514. }, predicate, fastCheck);
  28515. if (result) {
  28516. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28517. }
  28518. return result;
  28519. };
  28520. /** Launch a ray to try to pick a sprite in the scene
  28521. * @param x position on screen
  28522. * @param y position on screen
  28523. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28524. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28525. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28526. * @returns a PickingInfo
  28527. */
  28528. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28529. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28530. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28531. };
  28532. /** Use the given ray to pick a sprite in the scene
  28533. * @param ray The ray (in world space) to use to pick meshes
  28534. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28535. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28536. * @param camera camera to use. Can be set to null. In this case, the scene.activeCamera will be used
  28537. * @returns a PickingInfo
  28538. */
  28539. Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  28540. if (!this._cachedRayForTransform) {
  28541. this._cachedRayForTransform = BABYLON.Ray.Zero();
  28542. }
  28543. if (!camera) {
  28544. if (!this.activeCamera) {
  28545. return null;
  28546. }
  28547. camera = this.activeCamera;
  28548. }
  28549. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._cachedRayForTransform);
  28550. return this._internalPickSprites(this._cachedRayForTransform, predicate, fastCheck, camera);
  28551. };
  28552. /** Use the given ray to pick a mesh in the scene
  28553. * @param ray The ray to use to pick meshes
  28554. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28555. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28556. * @returns a PickingInfo
  28557. */
  28558. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28559. var _this = this;
  28560. var result = this._internalPick(function (world) {
  28561. if (!_this._pickWithRayInverseMatrix) {
  28562. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28563. }
  28564. world.invertToRef(_this._pickWithRayInverseMatrix);
  28565. if (!_this._cachedRayForTransform) {
  28566. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28567. }
  28568. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28569. return _this._cachedRayForTransform;
  28570. }, predicate, fastCheck);
  28571. if (result) {
  28572. result.ray = ray;
  28573. }
  28574. return result;
  28575. };
  28576. /**
  28577. * Launch a ray to try to pick a mesh in the scene
  28578. * @param x X position on screen
  28579. * @param y Y position on screen
  28580. * @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
  28581. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28582. * @returns an array of PickingInfo
  28583. */
  28584. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28585. var _this = this;
  28586. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28587. };
  28588. /**
  28589. * Launch a ray to try to pick a mesh in the scene
  28590. * @param ray Ray to use
  28591. * @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
  28592. * @returns an array of PickingInfo
  28593. */
  28594. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28595. var _this = this;
  28596. return this._internalMultiPick(function (world) {
  28597. if (!_this._pickWithRayInverseMatrix) {
  28598. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28599. }
  28600. world.invertToRef(_this._pickWithRayInverseMatrix);
  28601. if (!_this._cachedRayForTransform) {
  28602. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28603. }
  28604. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28605. return _this._cachedRayForTransform;
  28606. }, predicate);
  28607. };
  28608. /**
  28609. * Force the value of meshUnderPointer
  28610. * @param mesh defines the mesh to use
  28611. */
  28612. Scene.prototype.setPointerOverMesh = function (mesh) {
  28613. if (this._pointerOverMesh === mesh) {
  28614. return;
  28615. }
  28616. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28617. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28618. }
  28619. this._pointerOverMesh = mesh;
  28620. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28621. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28622. }
  28623. };
  28624. /**
  28625. * Gets the mesh under the pointer
  28626. * @returns a Mesh or null if no mesh is under the pointer
  28627. */
  28628. Scene.prototype.getPointerOverMesh = function () {
  28629. return this._pointerOverMesh;
  28630. };
  28631. /**
  28632. * Force the sprite under the pointer
  28633. * @param sprite defines the sprite to use
  28634. */
  28635. Scene.prototype.setPointerOverSprite = function (sprite) {
  28636. if (this._pointerOverSprite === sprite) {
  28637. return;
  28638. }
  28639. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28640. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28641. }
  28642. this._pointerOverSprite = sprite;
  28643. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28644. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28645. }
  28646. };
  28647. /**
  28648. * Gets the sprite under the pointer
  28649. * @returns a Sprite or null if no sprite is under the pointer
  28650. */
  28651. Scene.prototype.getPointerOverSprite = function () {
  28652. return this._pointerOverSprite;
  28653. };
  28654. // Physics
  28655. /**
  28656. * Gets the current physics engine
  28657. * @returns a PhysicsEngine or null if none attached
  28658. */
  28659. Scene.prototype.getPhysicsEngine = function () {
  28660. return this._physicsEngine;
  28661. };
  28662. /**
  28663. * Enables physics to the current scene
  28664. * @param gravity defines the scene's gravity for the physics engine
  28665. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28666. * @return a boolean indicating if the physics engine was initialized
  28667. */
  28668. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28669. if (gravity === void 0) { gravity = null; }
  28670. if (this._physicsEngine) {
  28671. return true;
  28672. }
  28673. try {
  28674. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28675. return true;
  28676. }
  28677. catch (e) {
  28678. BABYLON.Tools.Error(e.message);
  28679. return false;
  28680. }
  28681. };
  28682. /**
  28683. * Disables and disposes the physics engine associated with the scene
  28684. */
  28685. Scene.prototype.disablePhysicsEngine = function () {
  28686. if (!this._physicsEngine) {
  28687. return;
  28688. }
  28689. this._physicsEngine.dispose();
  28690. this._physicsEngine = null;
  28691. };
  28692. /**
  28693. * Gets a boolean indicating if there is an active physics engine
  28694. * @returns a boolean indicating if there is an active physics engine
  28695. */
  28696. Scene.prototype.isPhysicsEnabled = function () {
  28697. return this._physicsEngine !== undefined;
  28698. };
  28699. /**
  28700. * Deletes a physics compound impostor
  28701. * @param compound defines the compound to delete
  28702. */
  28703. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28704. var mesh = compound.parts[0].mesh;
  28705. if (mesh.physicsImpostor) {
  28706. mesh.physicsImpostor.dispose( /*true*/);
  28707. mesh.physicsImpostor = null;
  28708. }
  28709. };
  28710. // Misc.
  28711. /** @hidden */
  28712. Scene.prototype._rebuildGeometries = function () {
  28713. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28714. var geometry = _a[_i];
  28715. geometry._rebuild();
  28716. }
  28717. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28718. var mesh = _c[_b];
  28719. mesh._rebuild();
  28720. }
  28721. if (this.postProcessManager) {
  28722. this.postProcessManager._rebuild();
  28723. }
  28724. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28725. var component = _e[_d];
  28726. component.rebuild();
  28727. }
  28728. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28729. var system = _g[_f];
  28730. system.rebuild();
  28731. }
  28732. for (var _h = 0, _j = this._rebuildGeometryStage; _h < _j.length; _h++) {
  28733. var step = _j[_h];
  28734. step.action();
  28735. }
  28736. };
  28737. /** @hidden */
  28738. Scene.prototype._rebuildTextures = function () {
  28739. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28740. var texture = _a[_i];
  28741. texture._rebuild();
  28742. }
  28743. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28744. };
  28745. /**
  28746. * Creates a default light for the scene.
  28747. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-light
  28748. * @param replace has the default false, when true replaces the existing lights in the scene with a hemispheric light
  28749. */
  28750. Scene.prototype.createDefaultLight = function (replace) {
  28751. if (replace === void 0) { replace = false; }
  28752. // Dispose existing light in replace mode.
  28753. if (replace) {
  28754. if (this.lights) {
  28755. for (var i = 0; i < this.lights.length; i++) {
  28756. this.lights[i].dispose();
  28757. }
  28758. }
  28759. }
  28760. // Light
  28761. if (this.lights.length === 0) {
  28762. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28763. }
  28764. };
  28765. /**
  28766. * Creates a default camera for the scene.
  28767. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-camera
  28768. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28769. * @param replace has default false, when true replaces the active camera in the scene
  28770. * @param attachCameraControls has default false, when true attaches camera controls to the canvas.
  28771. */
  28772. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28773. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28774. if (replace === void 0) { replace = false; }
  28775. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28776. // Dispose existing camera in replace mode.
  28777. if (replace) {
  28778. if (this.activeCamera) {
  28779. this.activeCamera.dispose();
  28780. this.activeCamera = null;
  28781. }
  28782. }
  28783. // Camera
  28784. if (!this.activeCamera) {
  28785. var worldExtends = this.getWorldExtends();
  28786. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28787. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28788. var camera;
  28789. var radius = worldSize.length() * 1.5;
  28790. // empty scene scenario!
  28791. if (!isFinite(radius)) {
  28792. radius = 1;
  28793. worldCenter.copyFromFloats(0, 0, 0);
  28794. }
  28795. if (createArcRotateCamera) {
  28796. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28797. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28798. arcRotateCamera.wheelPrecision = 100 / radius;
  28799. camera = arcRotateCamera;
  28800. }
  28801. else {
  28802. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28803. freeCamera.setTarget(worldCenter);
  28804. camera = freeCamera;
  28805. }
  28806. camera.minZ = radius * 0.01;
  28807. camera.maxZ = radius * 1000;
  28808. camera.speed = radius * 0.2;
  28809. this.activeCamera = camera;
  28810. var canvas = this.getEngine().getRenderingCanvas();
  28811. if (attachCameraControls && canvas) {
  28812. camera.attachControl(canvas);
  28813. }
  28814. }
  28815. };
  28816. /**
  28817. * Creates a default camera and a default light.
  28818. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-camera-or-light
  28819. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28820. * @param replace has the default false, when true replaces the active camera/light in the scene
  28821. * @param attachCameraControls has the default false, when true attaches camera controls to the canvas.
  28822. */
  28823. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28824. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28825. if (replace === void 0) { replace = false; }
  28826. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28827. this.createDefaultLight(replace);
  28828. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28829. };
  28830. /**
  28831. * Creates a new sky box
  28832. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-skybox
  28833. * @param environmentTexture defines the texture to use as environment texture
  28834. * @param pbr has default false which requires the StandardMaterial to be used, when true PBRMaterial must be used
  28835. * @param scale defines the overall scale of the skybox
  28836. * @param blur is only available when pbr is true, default is 0, no blur, maximum value is 1
  28837. * @param setGlobalEnvTexture has default true indicating that scene.environmentTexture must match the current skybox texture
  28838. * @returns a new mesh holding the sky box
  28839. */
  28840. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28841. if (pbr === void 0) { pbr = false; }
  28842. if (scale === void 0) { scale = 1000; }
  28843. if (blur === void 0) { blur = 0; }
  28844. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28845. if (!environmentTexture) {
  28846. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28847. return null;
  28848. }
  28849. if (setGlobalEnvTexture) {
  28850. if (environmentTexture) {
  28851. this.environmentTexture = environmentTexture;
  28852. }
  28853. }
  28854. // Skybox
  28855. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28856. if (pbr) {
  28857. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28858. hdrSkyboxMaterial.backFaceCulling = false;
  28859. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28860. if (hdrSkyboxMaterial.reflectionTexture) {
  28861. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28862. }
  28863. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28864. hdrSkyboxMaterial.disableLighting = true;
  28865. hdrSkyboxMaterial.twoSidedLighting = true;
  28866. hdrSkybox.infiniteDistance = true;
  28867. hdrSkybox.material = hdrSkyboxMaterial;
  28868. }
  28869. else {
  28870. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28871. skyboxMaterial.backFaceCulling = false;
  28872. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28873. if (skyboxMaterial.reflectionTexture) {
  28874. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28875. }
  28876. skyboxMaterial.disableLighting = true;
  28877. hdrSkybox.infiniteDistance = true;
  28878. hdrSkybox.material = skyboxMaterial;
  28879. }
  28880. return hdrSkybox;
  28881. };
  28882. /**
  28883. * Creates a new environment
  28884. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-environment
  28885. * @param options defines the options you can use to configure the environment
  28886. * @returns the new EnvironmentHelper
  28887. */
  28888. Scene.prototype.createDefaultEnvironment = function (options) {
  28889. if (BABYLON.EnvironmentHelper) {
  28890. return new BABYLON.EnvironmentHelper(options, this);
  28891. }
  28892. return null;
  28893. };
  28894. /**
  28895. * Creates a new VREXperienceHelper
  28896. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28897. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28898. * @returns a new VREXperienceHelper
  28899. */
  28900. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28901. if (webVROptions === void 0) { webVROptions = {}; }
  28902. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28903. };
  28904. // Tags
  28905. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28906. if (tagsQuery === undefined) {
  28907. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28908. return list;
  28909. }
  28910. var listByTags = [];
  28911. forEach = forEach || (function (item) { return; });
  28912. for (var i in list) {
  28913. var item = list[i];
  28914. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28915. listByTags.push(item);
  28916. forEach(item);
  28917. }
  28918. }
  28919. return listByTags;
  28920. };
  28921. /**
  28922. * Get a list of meshes by tags
  28923. * @param tagsQuery defines the tags query to use
  28924. * @param forEach defines a predicate used to filter results
  28925. * @returns an array of Mesh
  28926. */
  28927. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28928. return this._getByTags(this.meshes, tagsQuery, forEach);
  28929. };
  28930. /**
  28931. * Get a list of cameras by tags
  28932. * @param tagsQuery defines the tags query to use
  28933. * @param forEach defines a predicate used to filter results
  28934. * @returns an array of Camera
  28935. */
  28936. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28937. return this._getByTags(this.cameras, tagsQuery, forEach);
  28938. };
  28939. /**
  28940. * Get a list of lights by tags
  28941. * @param tagsQuery defines the tags query to use
  28942. * @param forEach defines a predicate used to filter results
  28943. * @returns an array of Light
  28944. */
  28945. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28946. return this._getByTags(this.lights, tagsQuery, forEach);
  28947. };
  28948. /**
  28949. * Get a list of materials by tags
  28950. * @param tagsQuery defines the tags query to use
  28951. * @param forEach defines a predicate used to filter results
  28952. * @returns an array of Material
  28953. */
  28954. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28955. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28956. };
  28957. /**
  28958. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28959. * This allowed control for front to back rendering or reversly depending of the special needs.
  28960. *
  28961. * @param renderingGroupId The rendering group id corresponding to its index
  28962. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28963. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28964. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28965. */
  28966. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28967. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28968. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28969. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28970. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28971. };
  28972. /**
  28973. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28974. *
  28975. * @param renderingGroupId The rendering group id corresponding to its index
  28976. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28977. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28978. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28979. */
  28980. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28981. if (depth === void 0) { depth = true; }
  28982. if (stencil === void 0) { stencil = true; }
  28983. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28984. };
  28985. /**
  28986. * Gets the current auto clear configuration for one rendering group of the rendering
  28987. * manager.
  28988. * @param index the rendering group index to get the information for
  28989. * @returns The auto clear setup for the requested rendering group
  28990. */
  28991. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28992. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28993. };
  28994. /**
  28995. * Will flag all materials as dirty to trigger new shader compilation
  28996. * @param flag defines the flag used to specify which material part must be marked as dirty
  28997. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28998. */
  28999. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29000. if (this.blockMaterialDirtyMechanism) {
  29001. return;
  29002. }
  29003. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29004. var material = _a[_i];
  29005. if (predicate && !predicate(material)) {
  29006. continue;
  29007. }
  29008. material.markAsDirty(flag);
  29009. }
  29010. };
  29011. /** @hidden */
  29012. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29013. var _this = this;
  29014. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29015. this._activeRequests.push(request);
  29016. request.onCompleteObservable.add(function (request) {
  29017. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29018. });
  29019. return request;
  29020. };
  29021. /** @hidden */
  29022. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29023. var _this = this;
  29024. return new Promise(function (resolve, reject) {
  29025. _this._loadFile(url, function (data) {
  29026. resolve(data);
  29027. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29028. reject(exception);
  29029. });
  29030. });
  29031. };
  29032. // Statics
  29033. Scene._uniqueIdCounter = 0;
  29034. /** The fog is deactivated */
  29035. Scene.FOGMODE_NONE = 0;
  29036. /** The fog density is following an exponential function */
  29037. Scene.FOGMODE_EXP = 1;
  29038. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  29039. Scene.FOGMODE_EXP2 = 2;
  29040. /** The fog density is following a linear function. */
  29041. Scene.FOGMODE_LINEAR = 3;
  29042. /**
  29043. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29044. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29045. */
  29046. Scene.MinDeltaTime = 1.0;
  29047. /**
  29048. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29049. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29050. */
  29051. Scene.MaxDeltaTime = 1000.0;
  29052. /** The distance in pixel that you have to move to prevent some events */
  29053. Scene.DragMovementThreshold = 10; // in pixels
  29054. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29055. Scene.LongPressDelay = 500; // in milliseconds
  29056. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29057. Scene.DoubleClickDelay = 300; // in milliseconds
  29058. /** If you need to check double click without raising a single click at first click, enable this flag */
  29059. Scene.ExclusiveDoubleClickMode = false;
  29060. return Scene;
  29061. }(BABYLON.AbstractScene));
  29062. BABYLON.Scene = Scene;
  29063. })(BABYLON || (BABYLON = {}));
  29064. //# sourceMappingURL=babylon.scene.js.map
  29065. var BABYLON;
  29066. (function (BABYLON) {
  29067. /**
  29068. * Set of assets to keep when moving a scene into an asset container.
  29069. */
  29070. var KeepAssets = /** @class */ (function (_super) {
  29071. __extends(KeepAssets, _super);
  29072. function KeepAssets() {
  29073. return _super !== null && _super.apply(this, arguments) || this;
  29074. }
  29075. return KeepAssets;
  29076. }(BABYLON.AbstractScene));
  29077. BABYLON.KeepAssets = KeepAssets;
  29078. /**
  29079. * Container with a set of assets that can be added or removed from a scene.
  29080. */
  29081. var AssetContainer = /** @class */ (function (_super) {
  29082. __extends(AssetContainer, _super);
  29083. /**
  29084. * Instantiates an AssetContainer.
  29085. * @param scene The scene the AssetContainer belongs to.
  29086. */
  29087. function AssetContainer(scene) {
  29088. var _this = _super.call(this) || this;
  29089. _this.scene = scene;
  29090. return _this;
  29091. }
  29092. /**
  29093. * Adds all the assets from the container to the scene.
  29094. */
  29095. AssetContainer.prototype.addAllToScene = function () {
  29096. var _this = this;
  29097. this.cameras.forEach(function (o) {
  29098. _this.scene.addCamera(o);
  29099. });
  29100. this.lights.forEach(function (o) {
  29101. _this.scene.addLight(o);
  29102. });
  29103. this.meshes.forEach(function (o) {
  29104. _this.scene.addMesh(o);
  29105. });
  29106. this.skeletons.forEach(function (o) {
  29107. _this.scene.addSkeleton(o);
  29108. });
  29109. this.animations.forEach(function (o) {
  29110. _this.scene.addAnimation(o);
  29111. });
  29112. this.animationGroups.forEach(function (o) {
  29113. _this.scene.addAnimationGroup(o);
  29114. });
  29115. this.multiMaterials.forEach(function (o) {
  29116. _this.scene.addMultiMaterial(o);
  29117. });
  29118. this.materials.forEach(function (o) {
  29119. _this.scene.addMaterial(o);
  29120. });
  29121. this.morphTargetManagers.forEach(function (o) {
  29122. _this.scene.addMorphTargetManager(o);
  29123. });
  29124. this.geometries.forEach(function (o) {
  29125. _this.scene.addGeometry(o);
  29126. });
  29127. this.transformNodes.forEach(function (o) {
  29128. _this.scene.addTransformNode(o);
  29129. });
  29130. this.actionManagers.forEach(function (o) {
  29131. _this.scene.addActionManager(o);
  29132. });
  29133. this.sounds.forEach(function (o) {
  29134. o.play();
  29135. o.autoplay = true;
  29136. _this.scene.mainSoundTrack.AddSound(o);
  29137. });
  29138. this.textures.forEach(function (o) {
  29139. _this.scene.addTexture(o);
  29140. });
  29141. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29142. var component = _a[_i];
  29143. component.addFromContainer(this.scene);
  29144. }
  29145. };
  29146. /**
  29147. * Removes all the assets in the container from the scene
  29148. */
  29149. AssetContainer.prototype.removeAllFromScene = function () {
  29150. var _this = this;
  29151. this.cameras.forEach(function (o) {
  29152. _this.scene.removeCamera(o);
  29153. });
  29154. this.lights.forEach(function (o) {
  29155. _this.scene.removeLight(o);
  29156. });
  29157. this.meshes.forEach(function (o) {
  29158. _this.scene.removeMesh(o);
  29159. });
  29160. this.skeletons.forEach(function (o) {
  29161. _this.scene.removeSkeleton(o);
  29162. });
  29163. this.animations.forEach(function (o) {
  29164. _this.scene.removeAnimation(o);
  29165. });
  29166. this.animationGroups.forEach(function (o) {
  29167. _this.scene.removeAnimationGroup(o);
  29168. });
  29169. this.multiMaterials.forEach(function (o) {
  29170. _this.scene.removeMultiMaterial(o);
  29171. });
  29172. this.materials.forEach(function (o) {
  29173. _this.scene.removeMaterial(o);
  29174. });
  29175. this.morphTargetManagers.forEach(function (o) {
  29176. _this.scene.removeMorphTargetManager(o);
  29177. });
  29178. this.geometries.forEach(function (o) {
  29179. _this.scene.removeGeometry(o);
  29180. });
  29181. this.transformNodes.forEach(function (o) {
  29182. _this.scene.removeTransformNode(o);
  29183. });
  29184. this.actionManagers.forEach(function (o) {
  29185. _this.scene.removeActionManager(o);
  29186. });
  29187. this.sounds.forEach(function (o) {
  29188. o.stop();
  29189. o.autoplay = false;
  29190. _this.scene.mainSoundTrack.RemoveSound(o);
  29191. });
  29192. this.textures.forEach(function (o) {
  29193. _this.scene.removeTexture(o);
  29194. });
  29195. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29196. var component = _a[_i];
  29197. component.removeFromContainer(this.scene);
  29198. }
  29199. };
  29200. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29201. if (!sourceAssets) {
  29202. return;
  29203. }
  29204. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29205. var asset = sourceAssets_1[_i];
  29206. var move = true;
  29207. if (keepAssets) {
  29208. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29209. var keepAsset = keepAssets_1[_a];
  29210. if (asset === keepAsset) {
  29211. move = false;
  29212. break;
  29213. }
  29214. }
  29215. }
  29216. if (move) {
  29217. targetAssets.push(asset);
  29218. }
  29219. }
  29220. };
  29221. /**
  29222. * Removes all the assets contained in the scene and adds them to the container.
  29223. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29224. */
  29225. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29226. if (keepAssets === undefined) {
  29227. keepAssets = new KeepAssets();
  29228. }
  29229. for (var key in this) {
  29230. if (this.hasOwnProperty(key)) {
  29231. this[key] = this[key] || [];
  29232. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29233. }
  29234. }
  29235. this.removeAllFromScene();
  29236. };
  29237. /**
  29238. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  29239. * @returns the root mesh
  29240. */
  29241. AssetContainer.prototype.createRootMesh = function () {
  29242. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29243. this.meshes.forEach(function (m) {
  29244. if (!m.parent) {
  29245. rootMesh.addChild(m);
  29246. }
  29247. });
  29248. this.meshes.unshift(rootMesh);
  29249. return rootMesh;
  29250. };
  29251. return AssetContainer;
  29252. }(BABYLON.AbstractScene));
  29253. BABYLON.AssetContainer = AssetContainer;
  29254. })(BABYLON || (BABYLON = {}));
  29255. //# sourceMappingURL=babylon.assetContainer.js.map
  29256. var BABYLON;
  29257. (function (BABYLON) {
  29258. var Buffer = /** @class */ (function () {
  29259. /**
  29260. * Constructor
  29261. * @param engine the engine
  29262. * @param data the data to use for this buffer
  29263. * @param updatable whether the data is updatable
  29264. * @param stride the stride (optional)
  29265. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29266. * @param instanced whether the buffer is instanced (optional)
  29267. * @param useBytes set to true if the stride in in bytes (optional)
  29268. */
  29269. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29270. if (stride === void 0) { stride = 0; }
  29271. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29272. if (instanced === void 0) { instanced = false; }
  29273. if (useBytes === void 0) { useBytes = false; }
  29274. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29275. this._engine = engine.getScene().getEngine();
  29276. }
  29277. else {
  29278. this._engine = engine;
  29279. }
  29280. this._updatable = updatable;
  29281. this._instanced = instanced;
  29282. this._data = data;
  29283. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29284. if (!postponeInternalCreation) { // by default
  29285. this.create();
  29286. }
  29287. }
  29288. /**
  29289. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29290. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29291. * @param offset defines offset in the buffer (0 by default)
  29292. * @param size defines the size in floats of attributes (position is 3 for instance)
  29293. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29294. * @param instanced defines if the vertex buffer contains indexed data
  29295. * @param useBytes defines if the offset and stride are in bytes
  29296. * @returns the new vertex buffer
  29297. */
  29298. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29299. if (useBytes === void 0) { useBytes = false; }
  29300. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29301. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29302. // a lot of these parameters are ignored as they are overriden by the buffer
  29303. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29304. };
  29305. // Properties
  29306. Buffer.prototype.isUpdatable = function () {
  29307. return this._updatable;
  29308. };
  29309. Buffer.prototype.getData = function () {
  29310. return this._data;
  29311. };
  29312. Buffer.prototype.getBuffer = function () {
  29313. return this._buffer;
  29314. };
  29315. /**
  29316. * Gets the stride in float32 units (i.e. byte stride / 4).
  29317. * May not be an integer if the byte stride is not divisible by 4.
  29318. * DEPRECATED. Use byteStride instead.
  29319. * @returns the stride in float32 units
  29320. */
  29321. Buffer.prototype.getStrideSize = function () {
  29322. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29323. };
  29324. // Methods
  29325. Buffer.prototype.create = function (data) {
  29326. if (data === void 0) { data = null; }
  29327. if (!data && this._buffer) {
  29328. return; // nothing to do
  29329. }
  29330. data = data || this._data;
  29331. if (!data) {
  29332. return;
  29333. }
  29334. if (!this._buffer) { // create buffer
  29335. if (this._updatable) {
  29336. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29337. this._data = data;
  29338. }
  29339. else {
  29340. this._buffer = this._engine.createVertexBuffer(data);
  29341. }
  29342. }
  29343. else if (this._updatable) { // update buffer
  29344. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29345. this._data = data;
  29346. }
  29347. };
  29348. /** @hidden */
  29349. Buffer.prototype._rebuild = function () {
  29350. this._buffer = null;
  29351. this.create(this._data);
  29352. };
  29353. Buffer.prototype.update = function (data) {
  29354. this.create(data);
  29355. };
  29356. /**
  29357. * Updates the data directly.
  29358. * @param data the new data
  29359. * @param offset the new offset
  29360. * @param vertexCount the vertex count (optional)
  29361. * @param useBytes set to true if the offset is in bytes
  29362. */
  29363. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29364. if (useBytes === void 0) { useBytes = false; }
  29365. if (!this._buffer) {
  29366. return;
  29367. }
  29368. if (this._updatable) { // update buffer
  29369. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29370. this._data = null;
  29371. }
  29372. };
  29373. Buffer.prototype.dispose = function () {
  29374. if (!this._buffer) {
  29375. return;
  29376. }
  29377. if (this._engine._releaseBuffer(this._buffer)) {
  29378. this._buffer = null;
  29379. }
  29380. };
  29381. return Buffer;
  29382. }());
  29383. BABYLON.Buffer = Buffer;
  29384. })(BABYLON || (BABYLON = {}));
  29385. //# sourceMappingURL=babylon.buffer.js.map
  29386. var BABYLON;
  29387. (function (BABYLON) {
  29388. var VertexBuffer = /** @class */ (function () {
  29389. /**
  29390. * Constructor
  29391. * @param engine the engine
  29392. * @param data the data to use for this vertex buffer
  29393. * @param kind the vertex buffer kind
  29394. * @param updatable whether the data is updatable
  29395. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29396. * @param stride the stride (optional)
  29397. * @param instanced whether the buffer is instanced (optional)
  29398. * @param offset the offset of the data (optional)
  29399. * @param size the number of components (optional)
  29400. * @param type the type of the component (optional)
  29401. * @param normalized whether the data contains normalized data (optional)
  29402. * @param useBytes set to true if stride and offset are in bytes (optional)
  29403. */
  29404. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29405. if (normalized === void 0) { normalized = false; }
  29406. if (useBytes === void 0) { useBytes = false; }
  29407. if (data instanceof BABYLON.Buffer) {
  29408. this._buffer = data;
  29409. this._ownsBuffer = false;
  29410. }
  29411. else {
  29412. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29413. this._ownsBuffer = true;
  29414. }
  29415. this._kind = kind;
  29416. if (type == undefined) {
  29417. var data_1 = this.getData();
  29418. this.type = VertexBuffer.FLOAT;
  29419. if (data_1 instanceof Int8Array)
  29420. this.type = VertexBuffer.BYTE;
  29421. else if (data_1 instanceof Uint8Array)
  29422. this.type = VertexBuffer.UNSIGNED_BYTE;
  29423. else if (data_1 instanceof Int16Array)
  29424. this.type = VertexBuffer.SHORT;
  29425. else if (data_1 instanceof Uint16Array)
  29426. this.type = VertexBuffer.UNSIGNED_SHORT;
  29427. else if (data_1 instanceof Int32Array)
  29428. this.type = VertexBuffer.INT;
  29429. else if (data_1 instanceof Uint32Array)
  29430. this.type = VertexBuffer.UNSIGNED_INT;
  29431. }
  29432. else {
  29433. this.type = type;
  29434. }
  29435. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29436. if (useBytes) {
  29437. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29438. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29439. this.byteOffset = offset || 0;
  29440. }
  29441. else {
  29442. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29443. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29444. this.byteOffset = (offset || 0) * typeByteLength;
  29445. }
  29446. this.normalized = normalized;
  29447. this._instanced = instanced !== undefined ? instanced : false;
  29448. this._instanceDivisor = instanced ? 1 : 0;
  29449. }
  29450. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29451. /**
  29452. * Gets or sets the instance divisor when in instanced mode
  29453. */
  29454. get: function () {
  29455. return this._instanceDivisor;
  29456. },
  29457. set: function (value) {
  29458. this._instanceDivisor = value;
  29459. if (value == 0) {
  29460. this._instanced = false;
  29461. }
  29462. else {
  29463. this._instanced = true;
  29464. }
  29465. },
  29466. enumerable: true,
  29467. configurable: true
  29468. });
  29469. /** @hidden */
  29470. VertexBuffer.prototype._rebuild = function () {
  29471. if (!this._buffer) {
  29472. return;
  29473. }
  29474. this._buffer._rebuild();
  29475. };
  29476. /**
  29477. * Returns the kind of the VertexBuffer (string).
  29478. */
  29479. VertexBuffer.prototype.getKind = function () {
  29480. return this._kind;
  29481. };
  29482. // Properties
  29483. /**
  29484. * Boolean : is the VertexBuffer updatable ?
  29485. */
  29486. VertexBuffer.prototype.isUpdatable = function () {
  29487. return this._buffer.isUpdatable();
  29488. };
  29489. /**
  29490. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29491. */
  29492. VertexBuffer.prototype.getData = function () {
  29493. return this._buffer.getData();
  29494. };
  29495. /**
  29496. * Returns the WebGLBuffer associated to the VertexBuffer.
  29497. */
  29498. VertexBuffer.prototype.getBuffer = function () {
  29499. return this._buffer.getBuffer();
  29500. };
  29501. /**
  29502. * Returns the stride as a multiple of the type byte length.
  29503. * DEPRECATED. Use byteStride instead.
  29504. */
  29505. VertexBuffer.prototype.getStrideSize = function () {
  29506. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29507. };
  29508. /**
  29509. * Returns the offset as a multiple of the type byte length.
  29510. * DEPRECATED. Use byteOffset instead.
  29511. */
  29512. VertexBuffer.prototype.getOffset = function () {
  29513. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29514. };
  29515. /**
  29516. * Returns the number of components per vertex attribute (integer).
  29517. */
  29518. VertexBuffer.prototype.getSize = function () {
  29519. return this._size;
  29520. };
  29521. /**
  29522. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29523. */
  29524. VertexBuffer.prototype.getIsInstanced = function () {
  29525. return this._instanced;
  29526. };
  29527. /**
  29528. * Returns the instancing divisor, zero for non-instanced (integer).
  29529. */
  29530. VertexBuffer.prototype.getInstanceDivisor = function () {
  29531. return this._instanceDivisor;
  29532. };
  29533. // Methods
  29534. /**
  29535. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29536. * Returns the created WebGLBuffer.
  29537. */
  29538. VertexBuffer.prototype.create = function (data) {
  29539. return this._buffer.create(data);
  29540. };
  29541. /**
  29542. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29543. * This function will create a new buffer if the current one is not updatable
  29544. * Returns the updated WebGLBuffer.
  29545. */
  29546. VertexBuffer.prototype.update = function (data) {
  29547. return this._buffer.update(data);
  29548. };
  29549. /**
  29550. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29551. * Returns the directly updated WebGLBuffer.
  29552. * @param data the new data
  29553. * @param offset the new offset
  29554. * @param useBytes set to true if the offset is in bytes
  29555. */
  29556. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29557. if (useBytes === void 0) { useBytes = false; }
  29558. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29559. };
  29560. /**
  29561. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29562. */
  29563. VertexBuffer.prototype.dispose = function () {
  29564. if (this._ownsBuffer) {
  29565. this._buffer.dispose();
  29566. }
  29567. };
  29568. /**
  29569. * Enumerates each value of this vertex buffer as numbers.
  29570. * @param count the number of values to enumerate
  29571. * @param callback the callback function called for each value
  29572. */
  29573. VertexBuffer.prototype.forEach = function (count, callback) {
  29574. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29575. };
  29576. Object.defineProperty(VertexBuffer, "PositionKind", {
  29577. get: function () {
  29578. return VertexBuffer._PositionKind;
  29579. },
  29580. enumerable: true,
  29581. configurable: true
  29582. });
  29583. Object.defineProperty(VertexBuffer, "NormalKind", {
  29584. get: function () {
  29585. return VertexBuffer._NormalKind;
  29586. },
  29587. enumerable: true,
  29588. configurable: true
  29589. });
  29590. Object.defineProperty(VertexBuffer, "TangentKind", {
  29591. get: function () {
  29592. return VertexBuffer._TangentKind;
  29593. },
  29594. enumerable: true,
  29595. configurable: true
  29596. });
  29597. Object.defineProperty(VertexBuffer, "UVKind", {
  29598. get: function () {
  29599. return VertexBuffer._UVKind;
  29600. },
  29601. enumerable: true,
  29602. configurable: true
  29603. });
  29604. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29605. get: function () {
  29606. return VertexBuffer._UV2Kind;
  29607. },
  29608. enumerable: true,
  29609. configurable: true
  29610. });
  29611. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29612. get: function () {
  29613. return VertexBuffer._UV3Kind;
  29614. },
  29615. enumerable: true,
  29616. configurable: true
  29617. });
  29618. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29619. get: function () {
  29620. return VertexBuffer._UV4Kind;
  29621. },
  29622. enumerable: true,
  29623. configurable: true
  29624. });
  29625. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29626. get: function () {
  29627. return VertexBuffer._UV5Kind;
  29628. },
  29629. enumerable: true,
  29630. configurable: true
  29631. });
  29632. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29633. get: function () {
  29634. return VertexBuffer._UV6Kind;
  29635. },
  29636. enumerable: true,
  29637. configurable: true
  29638. });
  29639. Object.defineProperty(VertexBuffer, "ColorKind", {
  29640. get: function () {
  29641. return VertexBuffer._ColorKind;
  29642. },
  29643. enumerable: true,
  29644. configurable: true
  29645. });
  29646. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29647. get: function () {
  29648. return VertexBuffer._MatricesIndicesKind;
  29649. },
  29650. enumerable: true,
  29651. configurable: true
  29652. });
  29653. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29654. get: function () {
  29655. return VertexBuffer._MatricesWeightsKind;
  29656. },
  29657. enumerable: true,
  29658. configurable: true
  29659. });
  29660. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29661. get: function () {
  29662. return VertexBuffer._MatricesIndicesExtraKind;
  29663. },
  29664. enumerable: true,
  29665. configurable: true
  29666. });
  29667. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29668. get: function () {
  29669. return VertexBuffer._MatricesWeightsExtraKind;
  29670. },
  29671. enumerable: true,
  29672. configurable: true
  29673. });
  29674. /**
  29675. * Deduces the stride given a kind.
  29676. * @param kind The kind string to deduce
  29677. * @returns The deduced stride
  29678. */
  29679. VertexBuffer.DeduceStride = function (kind) {
  29680. switch (kind) {
  29681. case VertexBuffer.UVKind:
  29682. case VertexBuffer.UV2Kind:
  29683. case VertexBuffer.UV3Kind:
  29684. case VertexBuffer.UV4Kind:
  29685. case VertexBuffer.UV5Kind:
  29686. case VertexBuffer.UV6Kind:
  29687. return 2;
  29688. case VertexBuffer.NormalKind:
  29689. case VertexBuffer.PositionKind:
  29690. return 3;
  29691. case VertexBuffer.ColorKind:
  29692. case VertexBuffer.MatricesIndicesKind:
  29693. case VertexBuffer.MatricesIndicesExtraKind:
  29694. case VertexBuffer.MatricesWeightsKind:
  29695. case VertexBuffer.MatricesWeightsExtraKind:
  29696. case VertexBuffer.TangentKind:
  29697. return 4;
  29698. default:
  29699. throw new Error("Invalid kind '" + kind + "'");
  29700. }
  29701. };
  29702. /**
  29703. * Gets the byte length of the given type.
  29704. * @param type the type
  29705. * @returns the number of bytes
  29706. */
  29707. VertexBuffer.GetTypeByteLength = function (type) {
  29708. switch (type) {
  29709. case VertexBuffer.BYTE:
  29710. case VertexBuffer.UNSIGNED_BYTE:
  29711. return 1;
  29712. case VertexBuffer.SHORT:
  29713. case VertexBuffer.UNSIGNED_SHORT:
  29714. return 2;
  29715. case VertexBuffer.INT:
  29716. case VertexBuffer.FLOAT:
  29717. return 4;
  29718. default:
  29719. throw new Error("Invalid type '" + type + "'");
  29720. }
  29721. };
  29722. /**
  29723. * Enumerates each value of the given parameters as numbers.
  29724. * @param data the data to enumerate
  29725. * @param byteOffset the byte offset of the data
  29726. * @param byteStride the byte stride of the data
  29727. * @param componentCount the number of components per element
  29728. * @param componentType the type of the component
  29729. * @param count the total number of components
  29730. * @param normalized whether the data is normalized
  29731. * @param callback the callback function called for each value
  29732. */
  29733. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29734. if (data instanceof Array) {
  29735. var offset = byteOffset / 4;
  29736. var stride = byteStride / 4;
  29737. for (var index = 0; index < count; index += componentCount) {
  29738. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29739. callback(data[offset + componentIndex], index + componentIndex);
  29740. }
  29741. offset += stride;
  29742. }
  29743. }
  29744. else {
  29745. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29746. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29747. for (var index = 0; index < count; index += componentCount) {
  29748. var componentByteOffset = byteOffset;
  29749. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29750. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29751. callback(value, index + componentIndex);
  29752. componentByteOffset += componentByteLength;
  29753. }
  29754. byteOffset += byteStride;
  29755. }
  29756. }
  29757. };
  29758. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29759. switch (type) {
  29760. case VertexBuffer.BYTE: {
  29761. var value = dataView.getInt8(byteOffset);
  29762. if (normalized) {
  29763. value = Math.max(value / 127, -1);
  29764. }
  29765. return value;
  29766. }
  29767. case VertexBuffer.UNSIGNED_BYTE: {
  29768. var value = dataView.getUint8(byteOffset);
  29769. if (normalized) {
  29770. value = value / 255;
  29771. }
  29772. return value;
  29773. }
  29774. case VertexBuffer.SHORT: {
  29775. var value = dataView.getInt16(byteOffset, true);
  29776. if (normalized) {
  29777. value = Math.max(value / 16383, -1);
  29778. }
  29779. return value;
  29780. }
  29781. case VertexBuffer.UNSIGNED_SHORT: {
  29782. var value = dataView.getUint16(byteOffset, true);
  29783. if (normalized) {
  29784. value = value / 65535;
  29785. }
  29786. return value;
  29787. }
  29788. case VertexBuffer.FLOAT: {
  29789. return dataView.getFloat32(byteOffset, true);
  29790. }
  29791. default: {
  29792. throw new Error("Invalid component type " + type);
  29793. }
  29794. }
  29795. };
  29796. /**
  29797. * The byte type.
  29798. */
  29799. VertexBuffer.BYTE = 5120;
  29800. /**
  29801. * The unsigned byte type.
  29802. */
  29803. VertexBuffer.UNSIGNED_BYTE = 5121;
  29804. /**
  29805. * The short type.
  29806. */
  29807. VertexBuffer.SHORT = 5122;
  29808. /**
  29809. * The unsigned short type.
  29810. */
  29811. VertexBuffer.UNSIGNED_SHORT = 5123;
  29812. /**
  29813. * The integer type.
  29814. */
  29815. VertexBuffer.INT = 5124;
  29816. /**
  29817. * The unsigned integer type.
  29818. */
  29819. VertexBuffer.UNSIGNED_INT = 5125;
  29820. /**
  29821. * The float type.
  29822. */
  29823. VertexBuffer.FLOAT = 5126;
  29824. // Enums
  29825. VertexBuffer._PositionKind = "position";
  29826. VertexBuffer._NormalKind = "normal";
  29827. VertexBuffer._TangentKind = "tangent";
  29828. VertexBuffer._UVKind = "uv";
  29829. VertexBuffer._UV2Kind = "uv2";
  29830. VertexBuffer._UV3Kind = "uv3";
  29831. VertexBuffer._UV4Kind = "uv4";
  29832. VertexBuffer._UV5Kind = "uv5";
  29833. VertexBuffer._UV6Kind = "uv6";
  29834. VertexBuffer._ColorKind = "color";
  29835. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29836. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29837. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29838. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29839. return VertexBuffer;
  29840. }());
  29841. BABYLON.VertexBuffer = VertexBuffer;
  29842. })(BABYLON || (BABYLON = {}));
  29843. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29844. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29845. var BABYLON;
  29846. (function (BABYLON) {
  29847. /**
  29848. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29849. */
  29850. var DummyInternalTextureTracker = /** @class */ (function () {
  29851. function DummyInternalTextureTracker() {
  29852. /**
  29853. * Gets or set the previous tracker in the list
  29854. */
  29855. this.previous = null;
  29856. /**
  29857. * Gets or set the next tracker in the list
  29858. */
  29859. this.next = null;
  29860. }
  29861. return DummyInternalTextureTracker;
  29862. }());
  29863. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29864. })(BABYLON || (BABYLON = {}));
  29865. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29866. var BABYLON;
  29867. (function (BABYLON) {
  29868. /**
  29869. * Class used to store data associated with WebGL texture data for the engine
  29870. * This class should not be used directly
  29871. */
  29872. var InternalTexture = /** @class */ (function () {
  29873. /**
  29874. * Creates a new InternalTexture
  29875. * @param engine defines the engine to use
  29876. * @param dataSource defines the type of data that will be used
  29877. */
  29878. function InternalTexture(engine, dataSource) {
  29879. /**
  29880. * Observable called when the texture is loaded
  29881. */
  29882. this.onLoadedObservable = new BABYLON.Observable();
  29883. /**
  29884. * Gets or set the previous tracker in the list
  29885. */
  29886. this.previous = null;
  29887. /**
  29888. * Gets or set the next tracker in the list
  29889. */
  29890. this.next = null;
  29891. // Private
  29892. /** @hidden */
  29893. this._initialSlot = -1;
  29894. /** @hidden */
  29895. this._designatedSlot = -1;
  29896. /** @hidden */
  29897. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29898. /** @hidden */
  29899. this._comparisonFunction = 0;
  29900. /** @hidden */
  29901. this._sphericalPolynomial = null;
  29902. /** @hidden */
  29903. this._lodGenerationScale = 0;
  29904. /** @hidden */
  29905. this._lodGenerationOffset = 0;
  29906. /** @hidden */
  29907. this._isRGBD = false;
  29908. /** @hidden */
  29909. this._references = 1;
  29910. this._engine = engine;
  29911. this._dataSource = dataSource;
  29912. this._webGLTexture = engine._createTexture();
  29913. }
  29914. /**
  29915. * Gets the Engine the texture belongs to.
  29916. * @returns The babylon engine
  29917. */
  29918. InternalTexture.prototype.getEngine = function () {
  29919. return this._engine;
  29920. };
  29921. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29922. /**
  29923. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29924. */
  29925. get: function () {
  29926. return this._dataSource;
  29927. },
  29928. enumerable: true,
  29929. configurable: true
  29930. });
  29931. /**
  29932. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29933. */
  29934. InternalTexture.prototype.incrementReferences = function () {
  29935. this._references++;
  29936. };
  29937. /**
  29938. * Change the size of the texture (not the size of the content)
  29939. * @param width defines the new width
  29940. * @param height defines the new height
  29941. * @param depth defines the new depth (1 by default)
  29942. */
  29943. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29944. if (depth === void 0) { depth = 1; }
  29945. this.width = width;
  29946. this.height = height;
  29947. this.depth = depth;
  29948. this.baseWidth = width;
  29949. this.baseHeight = height;
  29950. this.baseDepth = depth;
  29951. this._size = width * height * depth;
  29952. };
  29953. /** @hidden */
  29954. InternalTexture.prototype._rebuild = function () {
  29955. var _this = this;
  29956. var proxy;
  29957. this.isReady = false;
  29958. this._cachedCoordinatesMode = null;
  29959. this._cachedWrapU = null;
  29960. this._cachedWrapV = null;
  29961. this._cachedAnisotropicFilteringLevel = null;
  29962. switch (this._dataSource) {
  29963. case InternalTexture.DATASOURCE_TEMP:
  29964. return;
  29965. case InternalTexture.DATASOURCE_URL:
  29966. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29967. _this.isReady = true;
  29968. }, null, this._buffer, undefined, this.format);
  29969. proxy._swapAndDie(this);
  29970. return;
  29971. case InternalTexture.DATASOURCE_RAW:
  29972. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29973. proxy._swapAndDie(this);
  29974. this.isReady = true;
  29975. return;
  29976. case InternalTexture.DATASOURCE_RAW3D:
  29977. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29978. proxy._swapAndDie(this);
  29979. this.isReady = true;
  29980. return;
  29981. case InternalTexture.DATASOURCE_DYNAMIC:
  29982. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29983. proxy._swapAndDie(this);
  29984. // The engine will make sure to update content so no need to flag it as isReady = true
  29985. return;
  29986. case InternalTexture.DATASOURCE_RENDERTARGET:
  29987. var options = new BABYLON.RenderTargetCreationOptions();
  29988. options.generateDepthBuffer = this._generateDepthBuffer;
  29989. options.generateMipMaps = this.generateMipMaps;
  29990. options.generateStencilBuffer = this._generateStencilBuffer;
  29991. options.samplingMode = this.samplingMode;
  29992. options.type = this.type;
  29993. if (this.isCube) {
  29994. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29995. }
  29996. else {
  29997. var size = {
  29998. width: this.width,
  29999. height: this.height
  30000. };
  30001. proxy = this._engine.createRenderTargetTexture(size, options);
  30002. }
  30003. proxy._swapAndDie(this);
  30004. this.isReady = true;
  30005. return;
  30006. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30007. var depthTextureOptions = {
  30008. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30009. comparisonFunction: this._comparisonFunction,
  30010. generateStencil: this._generateStencilBuffer,
  30011. isCube: this.isCube
  30012. };
  30013. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30014. proxy._swapAndDie(this);
  30015. this.isReady = true;
  30016. return;
  30017. case InternalTexture.DATASOURCE_CUBE:
  30018. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30019. _this.isReady = true;
  30020. }, null, this.format, this._extension);
  30021. proxy._swapAndDie(this);
  30022. return;
  30023. case InternalTexture.DATASOURCE_CUBERAW:
  30024. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30025. proxy._swapAndDie(this);
  30026. this.isReady = true;
  30027. return;
  30028. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30029. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30030. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30031. _this.isReady = true;
  30032. });
  30033. proxy._swapAndDie(this);
  30034. return;
  30035. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30036. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30037. if (proxy) {
  30038. proxy._swapAndDie(_this);
  30039. }
  30040. _this.isReady = true;
  30041. }, null, this.format, this._extension);
  30042. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30043. return;
  30044. }
  30045. };
  30046. /** @hidden */
  30047. InternalTexture.prototype._swapAndDie = function (target) {
  30048. target._webGLTexture = this._webGLTexture;
  30049. if (this._framebuffer) {
  30050. target._framebuffer = this._framebuffer;
  30051. }
  30052. if (this._depthStencilBuffer) {
  30053. target._depthStencilBuffer = this._depthStencilBuffer;
  30054. }
  30055. if (this._lodTextureHigh) {
  30056. if (target._lodTextureHigh) {
  30057. target._lodTextureHigh.dispose();
  30058. }
  30059. target._lodTextureHigh = this._lodTextureHigh;
  30060. }
  30061. if (this._lodTextureMid) {
  30062. if (target._lodTextureMid) {
  30063. target._lodTextureMid.dispose();
  30064. }
  30065. target._lodTextureMid = this._lodTextureMid;
  30066. }
  30067. if (this._lodTextureLow) {
  30068. if (target._lodTextureLow) {
  30069. target._lodTextureLow.dispose();
  30070. }
  30071. target._lodTextureLow = this._lodTextureLow;
  30072. }
  30073. var cache = this._engine.getLoadedTexturesCache();
  30074. var index = cache.indexOf(this);
  30075. if (index !== -1) {
  30076. cache.splice(index, 1);
  30077. }
  30078. };
  30079. /**
  30080. * Dispose the current allocated resources
  30081. */
  30082. InternalTexture.prototype.dispose = function () {
  30083. if (!this._webGLTexture) {
  30084. return;
  30085. }
  30086. this._references--;
  30087. if (this._references === 0) {
  30088. this._engine._releaseTexture(this);
  30089. this._webGLTexture = null;
  30090. this.previous = null;
  30091. this.next = null;
  30092. }
  30093. };
  30094. /**
  30095. * The source of the texture data is unknown
  30096. */
  30097. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30098. /**
  30099. * Texture data comes from an URL
  30100. */
  30101. InternalTexture.DATASOURCE_URL = 1;
  30102. /**
  30103. * Texture data is only used for temporary storage
  30104. */
  30105. InternalTexture.DATASOURCE_TEMP = 2;
  30106. /**
  30107. * Texture data comes from raw data (ArrayBuffer)
  30108. */
  30109. InternalTexture.DATASOURCE_RAW = 3;
  30110. /**
  30111. * Texture content is dynamic (video or dynamic texture)
  30112. */
  30113. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30114. /**
  30115. * Texture content is generated by rendering to it
  30116. */
  30117. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30118. /**
  30119. * Texture content is part of a multi render target process
  30120. */
  30121. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30122. /**
  30123. * Texture data comes from a cube data file
  30124. */
  30125. InternalTexture.DATASOURCE_CUBE = 7;
  30126. /**
  30127. * Texture data comes from a raw cube data
  30128. */
  30129. InternalTexture.DATASOURCE_CUBERAW = 8;
  30130. /**
  30131. * Texture data come from a prefiltered cube data file
  30132. */
  30133. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30134. /**
  30135. * Texture content is raw 3D data
  30136. */
  30137. InternalTexture.DATASOURCE_RAW3D = 10;
  30138. /**
  30139. * Texture content is a depth texture
  30140. */
  30141. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30142. /**
  30143. * Texture data comes from a raw cube data encoded with RGBD
  30144. */
  30145. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30146. return InternalTexture;
  30147. }());
  30148. BABYLON.InternalTexture = InternalTexture;
  30149. })(BABYLON || (BABYLON = {}));
  30150. //# sourceMappingURL=babylon.internalTexture.js.map
  30151. var BABYLON;
  30152. (function (BABYLON) {
  30153. var BaseTexture = /** @class */ (function () {
  30154. function BaseTexture(scene) {
  30155. this._hasAlpha = false;
  30156. this.getAlphaFromRGB = false;
  30157. this.level = 1;
  30158. this.coordinatesIndex = 0;
  30159. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30160. /**
  30161. * | Value | Type | Description |
  30162. * | ----- | ------------------ | ----------- |
  30163. * | 0 | CLAMP_ADDRESSMODE | |
  30164. * | 1 | WRAP_ADDRESSMODE | |
  30165. * | 2 | MIRROR_ADDRESSMODE | |
  30166. */
  30167. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30168. /**
  30169. * | Value | Type | Description |
  30170. * | ----- | ------------------ | ----------- |
  30171. * | 0 | CLAMP_ADDRESSMODE | |
  30172. * | 1 | WRAP_ADDRESSMODE | |
  30173. * | 2 | MIRROR_ADDRESSMODE | |
  30174. */
  30175. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30176. /**
  30177. * | Value | Type | Description |
  30178. * | ----- | ------------------ | ----------- |
  30179. * | 0 | CLAMP_ADDRESSMODE | |
  30180. * | 1 | WRAP_ADDRESSMODE | |
  30181. * | 2 | MIRROR_ADDRESSMODE | |
  30182. */
  30183. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30184. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30185. this.isCube = false;
  30186. this.is3D = false;
  30187. this.gammaSpace = true;
  30188. this.invertZ = false;
  30189. this.lodLevelInAlpha = false;
  30190. this.isRenderTarget = false;
  30191. this.animations = new Array();
  30192. /**
  30193. * An event triggered when the texture is disposed.
  30194. */
  30195. this.onDisposeObservable = new BABYLON.Observable();
  30196. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30197. this._cachedSize = BABYLON.Size.Zero();
  30198. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30199. if (this._scene) {
  30200. this._scene.textures.push(this);
  30201. }
  30202. this._uid = null;
  30203. }
  30204. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30205. get: function () {
  30206. return this._hasAlpha;
  30207. },
  30208. set: function (value) {
  30209. if (this._hasAlpha === value) {
  30210. return;
  30211. }
  30212. this._hasAlpha = value;
  30213. if (this._scene) {
  30214. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30215. }
  30216. },
  30217. enumerable: true,
  30218. configurable: true
  30219. });
  30220. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30221. get: function () {
  30222. return this._coordinatesMode;
  30223. },
  30224. /**
  30225. * How a texture is mapped.
  30226. *
  30227. * | Value | Type | Description |
  30228. * | ----- | ----------------------------------- | ----------- |
  30229. * | 0 | EXPLICIT_MODE | |
  30230. * | 1 | SPHERICAL_MODE | |
  30231. * | 2 | PLANAR_MODE | |
  30232. * | 3 | CUBIC_MODE | |
  30233. * | 4 | PROJECTION_MODE | |
  30234. * | 5 | SKYBOX_MODE | |
  30235. * | 6 | INVCUBIC_MODE | |
  30236. * | 7 | EQUIRECTANGULAR_MODE | |
  30237. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30238. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30239. */
  30240. set: function (value) {
  30241. if (this._coordinatesMode === value) {
  30242. return;
  30243. }
  30244. this._coordinatesMode = value;
  30245. if (this._scene) {
  30246. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30247. }
  30248. },
  30249. enumerable: true,
  30250. configurable: true
  30251. });
  30252. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30253. /**
  30254. * Gets whether or not the texture contains RGBD data.
  30255. */
  30256. get: function () {
  30257. return this._texture != null && this._texture._isRGBD;
  30258. },
  30259. enumerable: true,
  30260. configurable: true
  30261. });
  30262. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30263. get: function () {
  30264. if (this._texture)
  30265. return this._texture._lodGenerationOffset;
  30266. return 0.0;
  30267. },
  30268. set: function (value) {
  30269. if (this._texture)
  30270. this._texture._lodGenerationOffset = value;
  30271. },
  30272. enumerable: true,
  30273. configurable: true
  30274. });
  30275. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30276. get: function () {
  30277. if (this._texture)
  30278. return this._texture._lodGenerationScale;
  30279. return 0.0;
  30280. },
  30281. set: function (value) {
  30282. if (this._texture)
  30283. this._texture._lodGenerationScale = value;
  30284. },
  30285. enumerable: true,
  30286. configurable: true
  30287. });
  30288. Object.defineProperty(BaseTexture.prototype, "uid", {
  30289. get: function () {
  30290. if (!this._uid) {
  30291. this._uid = BABYLON.Tools.RandomId();
  30292. }
  30293. return this._uid;
  30294. },
  30295. enumerable: true,
  30296. configurable: true
  30297. });
  30298. BaseTexture.prototype.toString = function () {
  30299. return this.name;
  30300. };
  30301. BaseTexture.prototype.getClassName = function () {
  30302. return "BaseTexture";
  30303. };
  30304. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30305. set: function (callback) {
  30306. if (this._onDisposeObserver) {
  30307. this.onDisposeObservable.remove(this._onDisposeObserver);
  30308. }
  30309. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30310. },
  30311. enumerable: true,
  30312. configurable: true
  30313. });
  30314. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30315. get: function () {
  30316. return true;
  30317. },
  30318. enumerable: true,
  30319. configurable: true
  30320. });
  30321. BaseTexture.prototype.getScene = function () {
  30322. return this._scene;
  30323. };
  30324. BaseTexture.prototype.getTextureMatrix = function () {
  30325. return BABYLON.Matrix.IdentityReadOnly;
  30326. };
  30327. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30328. return BABYLON.Matrix.IdentityReadOnly;
  30329. };
  30330. BaseTexture.prototype.getInternalTexture = function () {
  30331. return this._texture;
  30332. };
  30333. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30334. return !this.isBlocking || this.isReady();
  30335. };
  30336. BaseTexture.prototype.isReady = function () {
  30337. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30338. this.delayLoad();
  30339. return false;
  30340. }
  30341. if (this._texture) {
  30342. return this._texture.isReady;
  30343. }
  30344. return false;
  30345. };
  30346. BaseTexture.prototype.getSize = function () {
  30347. if (this._texture) {
  30348. if (this._texture.width) {
  30349. this._cachedSize.width = this._texture.width;
  30350. this._cachedSize.height = this._texture.height;
  30351. return this._cachedSize;
  30352. }
  30353. if (this._texture._size) {
  30354. this._cachedSize.width = this._texture._size;
  30355. this._cachedSize.height = this._texture._size;
  30356. return this._cachedSize;
  30357. }
  30358. }
  30359. return this._cachedSize;
  30360. };
  30361. BaseTexture.prototype.getBaseSize = function () {
  30362. if (!this.isReady() || !this._texture)
  30363. return BABYLON.Size.Zero();
  30364. if (this._texture._size) {
  30365. return new BABYLON.Size(this._texture._size, this._texture._size);
  30366. }
  30367. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30368. };
  30369. BaseTexture.prototype.scale = function (ratio) {
  30370. };
  30371. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30372. get: function () {
  30373. return false;
  30374. },
  30375. enumerable: true,
  30376. configurable: true
  30377. });
  30378. /** @hidden */
  30379. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30380. if (!this._scene) {
  30381. return null;
  30382. }
  30383. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30384. for (var index = 0; index < texturesCache.length; index++) {
  30385. var texturesCacheEntry = texturesCache[index];
  30386. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30387. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30388. texturesCacheEntry.incrementReferences();
  30389. return texturesCacheEntry;
  30390. }
  30391. }
  30392. }
  30393. return null;
  30394. };
  30395. /** @hidden */
  30396. BaseTexture.prototype._rebuild = function () {
  30397. };
  30398. BaseTexture.prototype.delayLoad = function () {
  30399. };
  30400. BaseTexture.prototype.clone = function () {
  30401. return null;
  30402. };
  30403. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30404. get: function () {
  30405. if (!this._texture) {
  30406. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30407. }
  30408. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30409. },
  30410. enumerable: true,
  30411. configurable: true
  30412. });
  30413. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30414. get: function () {
  30415. if (!this._texture) {
  30416. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30417. }
  30418. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30419. },
  30420. enumerable: true,
  30421. configurable: true
  30422. });
  30423. /**
  30424. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30425. * This will returns an RGBA array buffer containing either in values (0-255) or
  30426. * float values (0-1) depending of the underlying buffer type.
  30427. * @param faceIndex The face of the texture to read (in case of cube texture)
  30428. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30429. * @returns The Array buffer containing the pixels data.
  30430. */
  30431. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30432. if (faceIndex === void 0) { faceIndex = 0; }
  30433. if (level === void 0) { level = 0; }
  30434. if (!this._texture) {
  30435. return null;
  30436. }
  30437. var size = this.getSize();
  30438. var width = size.width;
  30439. var height = size.height;
  30440. var scene = this.getScene();
  30441. if (!scene) {
  30442. return null;
  30443. }
  30444. var engine = scene.getEngine();
  30445. if (level != 0) {
  30446. width = width / Math.pow(2, level);
  30447. height = height / Math.pow(2, level);
  30448. width = Math.round(width);
  30449. height = Math.round(height);
  30450. }
  30451. if (this._texture.isCube) {
  30452. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30453. }
  30454. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30455. };
  30456. BaseTexture.prototype.releaseInternalTexture = function () {
  30457. if (this._texture) {
  30458. this._texture.dispose();
  30459. this._texture = null;
  30460. }
  30461. };
  30462. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30463. get: function () {
  30464. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30465. return null;
  30466. }
  30467. if (!this._texture._sphericalPolynomial) {
  30468. this._texture._sphericalPolynomial =
  30469. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30470. }
  30471. return this._texture._sphericalPolynomial;
  30472. },
  30473. set: function (value) {
  30474. if (this._texture) {
  30475. this._texture._sphericalPolynomial = value;
  30476. }
  30477. },
  30478. enumerable: true,
  30479. configurable: true
  30480. });
  30481. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30482. get: function () {
  30483. if (this._texture) {
  30484. return this._texture._lodTextureHigh;
  30485. }
  30486. return null;
  30487. },
  30488. enumerable: true,
  30489. configurable: true
  30490. });
  30491. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30492. get: function () {
  30493. if (this._texture) {
  30494. return this._texture._lodTextureMid;
  30495. }
  30496. return null;
  30497. },
  30498. enumerable: true,
  30499. configurable: true
  30500. });
  30501. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30502. get: function () {
  30503. if (this._texture) {
  30504. return this._texture._lodTextureLow;
  30505. }
  30506. return null;
  30507. },
  30508. enumerable: true,
  30509. configurable: true
  30510. });
  30511. BaseTexture.prototype.dispose = function () {
  30512. if (!this._scene) {
  30513. return;
  30514. }
  30515. // Animations
  30516. this._scene.stopAnimation(this);
  30517. // Remove from scene
  30518. this._scene._removePendingData(this);
  30519. var index = this._scene.textures.indexOf(this);
  30520. if (index >= 0) {
  30521. this._scene.textures.splice(index, 1);
  30522. }
  30523. if (this._texture === undefined) {
  30524. return;
  30525. }
  30526. // Release
  30527. this.releaseInternalTexture();
  30528. // Callback
  30529. this.onDisposeObservable.notifyObservers(this);
  30530. this.onDisposeObservable.clear();
  30531. };
  30532. BaseTexture.prototype.serialize = function () {
  30533. if (!this.name) {
  30534. return null;
  30535. }
  30536. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30537. // Animations
  30538. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30539. return serializationObject;
  30540. };
  30541. BaseTexture.WhenAllReady = function (textures, callback) {
  30542. var numRemaining = textures.length;
  30543. if (numRemaining === 0) {
  30544. callback();
  30545. return;
  30546. }
  30547. var _loop_1 = function () {
  30548. texture = textures[i];
  30549. if (texture.isReady()) {
  30550. if (--numRemaining === 0) {
  30551. callback();
  30552. }
  30553. }
  30554. else {
  30555. onLoadObservable = texture.onLoadObservable;
  30556. var onLoadCallback_1 = function () {
  30557. onLoadObservable.removeCallback(onLoadCallback_1);
  30558. if (--numRemaining === 0) {
  30559. callback();
  30560. }
  30561. };
  30562. onLoadObservable.add(onLoadCallback_1);
  30563. }
  30564. };
  30565. var texture, onLoadObservable;
  30566. for (var i = 0; i < textures.length; i++) {
  30567. _loop_1();
  30568. }
  30569. };
  30570. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30571. __decorate([
  30572. BABYLON.serialize()
  30573. ], BaseTexture.prototype, "name", void 0);
  30574. __decorate([
  30575. BABYLON.serialize("hasAlpha")
  30576. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30577. __decorate([
  30578. BABYLON.serialize()
  30579. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30580. __decorate([
  30581. BABYLON.serialize()
  30582. ], BaseTexture.prototype, "level", void 0);
  30583. __decorate([
  30584. BABYLON.serialize()
  30585. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30586. __decorate([
  30587. BABYLON.serialize("coordinatesMode")
  30588. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30589. __decorate([
  30590. BABYLON.serialize()
  30591. ], BaseTexture.prototype, "wrapU", void 0);
  30592. __decorate([
  30593. BABYLON.serialize()
  30594. ], BaseTexture.prototype, "wrapV", void 0);
  30595. __decorate([
  30596. BABYLON.serialize()
  30597. ], BaseTexture.prototype, "wrapR", void 0);
  30598. __decorate([
  30599. BABYLON.serialize()
  30600. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30601. __decorate([
  30602. BABYLON.serialize()
  30603. ], BaseTexture.prototype, "isCube", void 0);
  30604. __decorate([
  30605. BABYLON.serialize()
  30606. ], BaseTexture.prototype, "is3D", void 0);
  30607. __decorate([
  30608. BABYLON.serialize()
  30609. ], BaseTexture.prototype, "gammaSpace", void 0);
  30610. __decorate([
  30611. BABYLON.serialize()
  30612. ], BaseTexture.prototype, "invertZ", void 0);
  30613. __decorate([
  30614. BABYLON.serialize()
  30615. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30616. __decorate([
  30617. BABYLON.serialize()
  30618. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30619. __decorate([
  30620. BABYLON.serialize()
  30621. ], BaseTexture.prototype, "lodGenerationScale", null);
  30622. __decorate([
  30623. BABYLON.serialize()
  30624. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30625. return BaseTexture;
  30626. }());
  30627. BABYLON.BaseTexture = BaseTexture;
  30628. })(BABYLON || (BABYLON = {}));
  30629. //# sourceMappingURL=babylon.baseTexture.js.map
  30630. var BABYLON;
  30631. (function (BABYLON) {
  30632. var Texture = /** @class */ (function (_super) {
  30633. __extends(Texture, _super);
  30634. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30635. if (noMipmap === void 0) { noMipmap = false; }
  30636. if (invertY === void 0) { invertY = true; }
  30637. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30638. if (onLoad === void 0) { onLoad = null; }
  30639. if (onError === void 0) { onError = null; }
  30640. if (buffer === void 0) { buffer = null; }
  30641. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30642. var _this = _super.call(this, scene) || this;
  30643. _this.uOffset = 0;
  30644. _this.vOffset = 0;
  30645. _this.uScale = 1.0;
  30646. _this.vScale = 1.0;
  30647. _this.uAng = 0;
  30648. _this.vAng = 0;
  30649. _this.wAng = 0;
  30650. /**
  30651. * Defines the center of rotation (U)
  30652. */
  30653. _this.uRotationCenter = 0.5;
  30654. /**
  30655. * Defines the center of rotation (V)
  30656. */
  30657. _this.vRotationCenter = 0.5;
  30658. /**
  30659. * Defines the center of rotation (W)
  30660. */
  30661. _this.wRotationCenter = 0.5;
  30662. _this._isBlocking = true;
  30663. _this.name = url || "";
  30664. _this.url = url;
  30665. _this._noMipmap = noMipmap;
  30666. _this._invertY = invertY;
  30667. _this._samplingMode = samplingMode;
  30668. _this._buffer = buffer;
  30669. _this._deleteBuffer = deleteBuffer;
  30670. if (format) {
  30671. _this._format = format;
  30672. }
  30673. scene = _this.getScene();
  30674. if (!scene) {
  30675. return _this;
  30676. }
  30677. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30678. var load = function () {
  30679. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30680. _this.onLoadObservable.notifyObservers(_this);
  30681. }
  30682. if (onLoad) {
  30683. onLoad();
  30684. }
  30685. if (!_this.isBlocking && scene) {
  30686. scene.resetCachedMaterial();
  30687. }
  30688. };
  30689. if (!_this.url) {
  30690. _this._delayedOnLoad = load;
  30691. _this._delayedOnError = onError;
  30692. return _this;
  30693. }
  30694. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30695. if (!_this._texture) {
  30696. if (!scene.useDelayedTextureLoading) {
  30697. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30698. if (deleteBuffer) {
  30699. delete _this._buffer;
  30700. }
  30701. }
  30702. else {
  30703. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30704. _this._delayedOnLoad = load;
  30705. _this._delayedOnError = onError;
  30706. }
  30707. }
  30708. else {
  30709. if (_this._texture.isReady) {
  30710. BABYLON.Tools.SetImmediate(function () { return load(); });
  30711. }
  30712. else {
  30713. _this._texture.onLoadedObservable.add(load);
  30714. }
  30715. }
  30716. return _this;
  30717. }
  30718. Object.defineProperty(Texture.prototype, "noMipmap", {
  30719. get: function () {
  30720. return this._noMipmap;
  30721. },
  30722. enumerable: true,
  30723. configurable: true
  30724. });
  30725. Object.defineProperty(Texture.prototype, "isBlocking", {
  30726. get: function () {
  30727. return this._isBlocking;
  30728. },
  30729. set: function (value) {
  30730. this._isBlocking = value;
  30731. },
  30732. enumerable: true,
  30733. configurable: true
  30734. });
  30735. Object.defineProperty(Texture.prototype, "samplingMode", {
  30736. get: function () {
  30737. return this._samplingMode;
  30738. },
  30739. enumerable: true,
  30740. configurable: true
  30741. });
  30742. /**
  30743. * Update the url (and optional buffer) of this texture if url was null during construction.
  30744. * @param url the url of the texture
  30745. * @param buffer the buffer of the texture (defaults to null)
  30746. */
  30747. Texture.prototype.updateURL = function (url, buffer) {
  30748. if (buffer === void 0) { buffer = null; }
  30749. if (this.url) {
  30750. throw new Error("URL is already set");
  30751. }
  30752. this.url = url;
  30753. this._buffer = buffer;
  30754. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30755. this.delayLoad();
  30756. };
  30757. Texture.prototype.delayLoad = function () {
  30758. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30759. return;
  30760. }
  30761. var scene = this.getScene();
  30762. if (!scene) {
  30763. return;
  30764. }
  30765. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30766. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30767. if (!this._texture) {
  30768. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30769. if (this._deleteBuffer) {
  30770. delete this._buffer;
  30771. }
  30772. }
  30773. else {
  30774. if (this._delayedOnLoad) {
  30775. if (this._texture.isReady) {
  30776. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30777. }
  30778. else {
  30779. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30780. }
  30781. }
  30782. }
  30783. this._delayedOnLoad = null;
  30784. this._delayedOnError = null;
  30785. };
  30786. /**
  30787. * Default is Trilinear mode.
  30788. *
  30789. * | Value | Type | Description |
  30790. * | ----- | ------------------ | ----------- |
  30791. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30792. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30793. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30794. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30795. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30796. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30797. * | 7 | NEAREST_LINEAR | |
  30798. * | 8 | NEAREST_NEAREST | |
  30799. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30800. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30801. * | 11 | LINEAR_LINEAR | |
  30802. * | 12 | LINEAR_NEAREST | |
  30803. *
  30804. * > _mag_: magnification filter (close to the viewer)
  30805. * > _min_: minification filter (far from the viewer)
  30806. * > _mip_: filter used between mip map levels
  30807. *
  30808. */
  30809. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30810. if (!this._texture) {
  30811. return;
  30812. }
  30813. var scene = this.getScene();
  30814. if (!scene) {
  30815. return;
  30816. }
  30817. this._samplingMode = samplingMode;
  30818. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30819. };
  30820. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30821. x *= this.uScale;
  30822. y *= this.vScale;
  30823. x -= this.uRotationCenter * this.uScale;
  30824. y -= this.vRotationCenter * this.vScale;
  30825. z -= this.wRotationCenter;
  30826. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30827. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30828. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30829. t.z += this.wRotationCenter;
  30830. };
  30831. Texture.prototype.getTextureMatrix = function () {
  30832. var _this = this;
  30833. if (this.uOffset === this._cachedUOffset &&
  30834. this.vOffset === this._cachedVOffset &&
  30835. this.uScale === this._cachedUScale &&
  30836. this.vScale === this._cachedVScale &&
  30837. this.uAng === this._cachedUAng &&
  30838. this.vAng === this._cachedVAng &&
  30839. this.wAng === this._cachedWAng) {
  30840. return this._cachedTextureMatrix;
  30841. }
  30842. this._cachedUOffset = this.uOffset;
  30843. this._cachedVOffset = this.vOffset;
  30844. this._cachedUScale = this.uScale;
  30845. this._cachedVScale = this.vScale;
  30846. this._cachedUAng = this.uAng;
  30847. this._cachedVAng = this.vAng;
  30848. this._cachedWAng = this.wAng;
  30849. if (!this._cachedTextureMatrix) {
  30850. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30851. this._rowGenerationMatrix = new BABYLON.Matrix();
  30852. this._t0 = BABYLON.Vector3.Zero();
  30853. this._t1 = BABYLON.Vector3.Zero();
  30854. this._t2 = BABYLON.Vector3.Zero();
  30855. }
  30856. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30857. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30858. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30859. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30860. this._t1.subtractInPlace(this._t0);
  30861. this._t2.subtractInPlace(this._t0);
  30862. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30863. this._cachedTextureMatrix.m[0] = this._t1.x;
  30864. this._cachedTextureMatrix.m[1] = this._t1.y;
  30865. this._cachedTextureMatrix.m[2] = this._t1.z;
  30866. this._cachedTextureMatrix.m[4] = this._t2.x;
  30867. this._cachedTextureMatrix.m[5] = this._t2.y;
  30868. this._cachedTextureMatrix.m[6] = this._t2.z;
  30869. this._cachedTextureMatrix.m[8] = this._t0.x;
  30870. this._cachedTextureMatrix.m[9] = this._t0.y;
  30871. this._cachedTextureMatrix.m[10] = this._t0.z;
  30872. var scene = this.getScene();
  30873. if (!scene) {
  30874. return this._cachedTextureMatrix;
  30875. }
  30876. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30877. return mat.hasTexture(_this);
  30878. });
  30879. return this._cachedTextureMatrix;
  30880. };
  30881. Texture.prototype.getReflectionTextureMatrix = function () {
  30882. var _this = this;
  30883. var scene = this.getScene();
  30884. if (!scene) {
  30885. return this._cachedTextureMatrix;
  30886. }
  30887. if (this.uOffset === this._cachedUOffset &&
  30888. this.vOffset === this._cachedVOffset &&
  30889. this.uScale === this._cachedUScale &&
  30890. this.vScale === this._cachedVScale &&
  30891. this.coordinatesMode === this._cachedCoordinatesMode) {
  30892. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30893. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30894. return this._cachedTextureMatrix;
  30895. }
  30896. }
  30897. else {
  30898. return this._cachedTextureMatrix;
  30899. }
  30900. }
  30901. if (!this._cachedTextureMatrix) {
  30902. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30903. }
  30904. if (!this._projectionModeMatrix) {
  30905. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30906. }
  30907. this._cachedUOffset = this.uOffset;
  30908. this._cachedVOffset = this.vOffset;
  30909. this._cachedUScale = this.uScale;
  30910. this._cachedVScale = this.vScale;
  30911. this._cachedCoordinatesMode = this.coordinatesMode;
  30912. switch (this.coordinatesMode) {
  30913. case Texture.PLANAR_MODE:
  30914. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30915. this._cachedTextureMatrix[0] = this.uScale;
  30916. this._cachedTextureMatrix[5] = this.vScale;
  30917. this._cachedTextureMatrix[12] = this.uOffset;
  30918. this._cachedTextureMatrix[13] = this.vOffset;
  30919. break;
  30920. case Texture.PROJECTION_MODE:
  30921. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30922. this._projectionModeMatrix.m[0] = 0.5;
  30923. this._projectionModeMatrix.m[5] = -0.5;
  30924. this._projectionModeMatrix.m[10] = 0.0;
  30925. this._projectionModeMatrix.m[12] = 0.5;
  30926. this._projectionModeMatrix.m[13] = 0.5;
  30927. this._projectionModeMatrix.m[14] = 1.0;
  30928. this._projectionModeMatrix.m[15] = 1.0;
  30929. var projectionMatrix = scene.getProjectionMatrix();
  30930. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30931. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30932. break;
  30933. default:
  30934. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30935. break;
  30936. }
  30937. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30938. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30939. });
  30940. return this._cachedTextureMatrix;
  30941. };
  30942. Texture.prototype.clone = function () {
  30943. var _this = this;
  30944. return BABYLON.SerializationHelper.Clone(function () {
  30945. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30946. }, this);
  30947. };
  30948. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30949. get: function () {
  30950. if (!this._onLoadObservable) {
  30951. this._onLoadObservable = new BABYLON.Observable();
  30952. }
  30953. return this._onLoadObservable;
  30954. },
  30955. enumerable: true,
  30956. configurable: true
  30957. });
  30958. Texture.prototype.serialize = function () {
  30959. var serializationObject = _super.prototype.serialize.call(this);
  30960. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30961. serializationObject.base64String = this._buffer;
  30962. serializationObject.name = serializationObject.name.replace("data:", "");
  30963. }
  30964. serializationObject.invertY = this._invertY;
  30965. serializationObject.samplingMode = this.samplingMode;
  30966. return serializationObject;
  30967. };
  30968. Texture.prototype.getClassName = function () {
  30969. return "Texture";
  30970. };
  30971. Texture.prototype.dispose = function () {
  30972. _super.prototype.dispose.call(this);
  30973. if (this._onLoadObservable) {
  30974. this._onLoadObservable.clear();
  30975. this._onLoadObservable = null;
  30976. }
  30977. this._delayedOnLoad = null;
  30978. this._delayedOnError = null;
  30979. };
  30980. // Statics
  30981. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30982. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30983. if (onLoad === void 0) { onLoad = null; }
  30984. if (onError === void 0) { onError = null; }
  30985. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30986. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30987. };
  30988. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30989. if (parsedTexture.customType) {
  30990. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30991. // Update Sampling Mode
  30992. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30993. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30994. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30995. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30996. }
  30997. }
  30998. return parsedCustomTexture;
  30999. }
  31000. if (parsedTexture.isCube) {
  31001. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31002. }
  31003. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31004. return null;
  31005. }
  31006. var texture = BABYLON.SerializationHelper.Parse(function () {
  31007. var generateMipMaps = true;
  31008. if (parsedTexture.noMipmap) {
  31009. generateMipMaps = false;
  31010. }
  31011. if (parsedTexture.mirrorPlane) {
  31012. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31013. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31014. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31015. return mirrorTexture;
  31016. }
  31017. else if (parsedTexture.isRenderTarget) {
  31018. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31019. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31020. return renderTargetTexture;
  31021. }
  31022. else {
  31023. var texture;
  31024. if (parsedTexture.base64String) {
  31025. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31026. }
  31027. else {
  31028. var url = rootUrl + parsedTexture.name;
  31029. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31030. url = parsedTexture.url;
  31031. }
  31032. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31033. }
  31034. return texture;
  31035. }
  31036. }, parsedTexture, scene);
  31037. // Update Sampling Mode
  31038. if (parsedTexture.samplingMode) {
  31039. var sampling = parsedTexture.samplingMode;
  31040. if (texture._samplingMode !== sampling) {
  31041. texture.updateSamplingMode(sampling);
  31042. }
  31043. }
  31044. // Animations
  31045. if (parsedTexture.animations) {
  31046. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31047. var parsedAnimation = parsedTexture.animations[animationIndex];
  31048. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31049. }
  31050. }
  31051. return texture;
  31052. };
  31053. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31054. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31055. if (noMipmap === void 0) { noMipmap = false; }
  31056. if (invertY === void 0) { invertY = true; }
  31057. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31058. if (onLoad === void 0) { onLoad = null; }
  31059. if (onError === void 0) { onError = null; }
  31060. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31061. if (name.substr(0, 5) !== "data:") {
  31062. name = "data:" + name;
  31063. }
  31064. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31065. };
  31066. // Constants
  31067. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  31068. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  31069. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  31070. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  31071. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  31072. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  31073. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  31074. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  31075. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  31076. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  31077. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  31078. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  31079. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  31080. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  31081. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  31082. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  31083. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  31084. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  31085. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  31086. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  31087. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  31088. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  31089. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  31090. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  31091. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  31092. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  31093. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  31094. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  31095. /**
  31096. * 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
  31097. */
  31098. Texture.UseSerializedUrlIfAny = false;
  31099. __decorate([
  31100. BABYLON.serialize()
  31101. ], Texture.prototype, "url", void 0);
  31102. __decorate([
  31103. BABYLON.serialize()
  31104. ], Texture.prototype, "uOffset", void 0);
  31105. __decorate([
  31106. BABYLON.serialize()
  31107. ], Texture.prototype, "vOffset", void 0);
  31108. __decorate([
  31109. BABYLON.serialize()
  31110. ], Texture.prototype, "uScale", void 0);
  31111. __decorate([
  31112. BABYLON.serialize()
  31113. ], Texture.prototype, "vScale", void 0);
  31114. __decorate([
  31115. BABYLON.serialize()
  31116. ], Texture.prototype, "uAng", void 0);
  31117. __decorate([
  31118. BABYLON.serialize()
  31119. ], Texture.prototype, "vAng", void 0);
  31120. __decorate([
  31121. BABYLON.serialize()
  31122. ], Texture.prototype, "wAng", void 0);
  31123. __decorate([
  31124. BABYLON.serialize()
  31125. ], Texture.prototype, "uRotationCenter", void 0);
  31126. __decorate([
  31127. BABYLON.serialize()
  31128. ], Texture.prototype, "vRotationCenter", void 0);
  31129. __decorate([
  31130. BABYLON.serialize()
  31131. ], Texture.prototype, "wRotationCenter", void 0);
  31132. __decorate([
  31133. BABYLON.serialize()
  31134. ], Texture.prototype, "isBlocking", null);
  31135. return Texture;
  31136. }(BABYLON.BaseTexture));
  31137. BABYLON.Texture = Texture;
  31138. })(BABYLON || (BABYLON = {}));
  31139. //# sourceMappingURL=babylon.texture.js.map
  31140. var BABYLON;
  31141. (function (BABYLON) {
  31142. /**
  31143. * @hidden
  31144. **/
  31145. var _InstancesBatch = /** @class */ (function () {
  31146. function _InstancesBatch() {
  31147. this.mustReturn = false;
  31148. this.visibleInstances = new Array();
  31149. this.renderSelf = new Array();
  31150. }
  31151. return _InstancesBatch;
  31152. }());
  31153. BABYLON._InstancesBatch = _InstancesBatch;
  31154. var Mesh = /** @class */ (function (_super) {
  31155. __extends(Mesh, _super);
  31156. /**
  31157. * @constructor
  31158. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31159. * @param {Scene} scene The scene to add this mesh to.
  31160. * @param {Node} parent The parent of this mesh, if it has one
  31161. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31162. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31163. * When false, achieved by calling a clone(), also passing False.
  31164. * This will make creation of children, recursive.
  31165. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31166. */
  31167. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31168. if (scene === void 0) { scene = null; }
  31169. if (parent === void 0) { parent = null; }
  31170. if (source === void 0) { source = null; }
  31171. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31172. var _this = _super.call(this, name, scene) || this;
  31173. // Members
  31174. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31175. _this.instances = new Array();
  31176. _this._LODLevels = new Array();
  31177. /** @hidden */
  31178. _this._visibleInstances = {};
  31179. _this._renderIdForInstances = new Array();
  31180. _this._batchCache = new _InstancesBatch();
  31181. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31182. // Use by builder only to know what orientation were the mesh build in.
  31183. /** @hidden */
  31184. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31185. _this.overrideMaterialSideOrientation = null;
  31186. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31187. // Will be used to save a source mesh reference, If any
  31188. _this._source = null;
  31189. scene = _this.getScene();
  31190. if (source) {
  31191. // Geometry
  31192. if (source._geometry) {
  31193. source._geometry.applyToMesh(_this);
  31194. }
  31195. // Deep copy
  31196. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31197. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  31198. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  31199. ], ["_poseMatrix"]);
  31200. // Source mesh
  31201. _this._source = source;
  31202. // Construction Params
  31203. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  31204. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  31205. var myAnyThis = _this;
  31206. var myAnySource = source;
  31207. myAnyThis._closePath = myAnySource._closePath;
  31208. myAnyThis._idx = myAnySource._idx;
  31209. myAnyThis.dashSize = myAnySource.dashSize;
  31210. myAnyThis.gapSize = myAnySource.gapSize;
  31211. myAnyThis.path3D = myAnySource.path3D;
  31212. myAnyThis.pathArray = myAnySource.pathArray;
  31213. myAnyThis.arc = myAnySource.arc;
  31214. myAnyThis.radius = myAnySource.radius;
  31215. // Animation ranges
  31216. if (_this._source._ranges) {
  31217. var ranges = _this._source._ranges;
  31218. for (var name in ranges) {
  31219. if (!ranges.hasOwnProperty(name)) {
  31220. continue;
  31221. }
  31222. if (!ranges[name]) {
  31223. continue;
  31224. }
  31225. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  31226. }
  31227. }
  31228. // Metadata
  31229. if (source.metadata && source.metadata.clone) {
  31230. _this.metadata = source.metadata.clone();
  31231. }
  31232. else {
  31233. _this.metadata = source.metadata;
  31234. }
  31235. // Tags
  31236. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31237. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31238. }
  31239. // Parent
  31240. _this.parent = source.parent;
  31241. // Pivot
  31242. _this.setPivotMatrix(source.getPivotMatrix());
  31243. _this.id = name + "." + source.id;
  31244. // Material
  31245. _this.material = source.material;
  31246. var index;
  31247. if (!doNotCloneChildren) {
  31248. // Children
  31249. var directDescendants = source.getDescendants(true);
  31250. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31251. var child = directDescendants[index_1];
  31252. if (child.clone) {
  31253. child.clone(name + "." + child.name, _this);
  31254. }
  31255. }
  31256. }
  31257. // Physics clone
  31258. var physicsEngine = _this.getScene().getPhysicsEngine();
  31259. if (clonePhysicsImpostor && physicsEngine) {
  31260. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31261. if (impostor) {
  31262. _this.physicsImpostor = impostor.clone(_this);
  31263. }
  31264. }
  31265. // Particles
  31266. for (index = 0; index < scene.particleSystems.length; index++) {
  31267. var system = scene.particleSystems[index];
  31268. if (system.emitter === source) {
  31269. system.clone(system.name, _this);
  31270. }
  31271. }
  31272. _this.refreshBoundingInfo();
  31273. _this.computeWorldMatrix(true);
  31274. }
  31275. // Parent
  31276. if (parent !== null) {
  31277. _this.parent = parent;
  31278. }
  31279. return _this;
  31280. }
  31281. Object.defineProperty(Mesh, "FRONTSIDE", {
  31282. /**
  31283. * Mesh side orientation : usually the external or front surface
  31284. */
  31285. get: function () {
  31286. return Mesh._FRONTSIDE;
  31287. },
  31288. enumerable: true,
  31289. configurable: true
  31290. });
  31291. Object.defineProperty(Mesh, "BACKSIDE", {
  31292. /**
  31293. * Mesh side orientation : usually the internal or back surface
  31294. */
  31295. get: function () {
  31296. return Mesh._BACKSIDE;
  31297. },
  31298. enumerable: true,
  31299. configurable: true
  31300. });
  31301. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31302. /**
  31303. * Mesh side orientation : both internal and external or front and back surfaces
  31304. */
  31305. get: function () {
  31306. return Mesh._DOUBLESIDE;
  31307. },
  31308. enumerable: true,
  31309. configurable: true
  31310. });
  31311. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31312. /**
  31313. * Mesh side orientation : by default, `FRONTSIDE`
  31314. */
  31315. get: function () {
  31316. return Mesh._DEFAULTSIDE;
  31317. },
  31318. enumerable: true,
  31319. configurable: true
  31320. });
  31321. Object.defineProperty(Mesh, "NO_CAP", {
  31322. /**
  31323. * Mesh cap setting : no cap
  31324. */
  31325. get: function () {
  31326. return Mesh._NO_CAP;
  31327. },
  31328. enumerable: true,
  31329. configurable: true
  31330. });
  31331. Object.defineProperty(Mesh, "CAP_START", {
  31332. /**
  31333. * Mesh cap setting : one cap at the beginning of the mesh
  31334. */
  31335. get: function () {
  31336. return Mesh._CAP_START;
  31337. },
  31338. enumerable: true,
  31339. configurable: true
  31340. });
  31341. Object.defineProperty(Mesh, "CAP_END", {
  31342. /**
  31343. * Mesh cap setting : one cap at the end of the mesh
  31344. */
  31345. get: function () {
  31346. return Mesh._CAP_END;
  31347. },
  31348. enumerable: true,
  31349. configurable: true
  31350. });
  31351. Object.defineProperty(Mesh, "CAP_ALL", {
  31352. /**
  31353. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31354. */
  31355. get: function () {
  31356. return Mesh._CAP_ALL;
  31357. },
  31358. enumerable: true,
  31359. configurable: true
  31360. });
  31361. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31362. /**
  31363. * An event triggered before rendering the mesh
  31364. */
  31365. get: function () {
  31366. if (!this._onBeforeRenderObservable) {
  31367. this._onBeforeRenderObservable = new BABYLON.Observable();
  31368. }
  31369. return this._onBeforeRenderObservable;
  31370. },
  31371. enumerable: true,
  31372. configurable: true
  31373. });
  31374. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31375. /**
  31376. * An event triggered after rendering the mesh
  31377. */
  31378. get: function () {
  31379. if (!this._onAfterRenderObservable) {
  31380. this._onAfterRenderObservable = new BABYLON.Observable();
  31381. }
  31382. return this._onAfterRenderObservable;
  31383. },
  31384. enumerable: true,
  31385. configurable: true
  31386. });
  31387. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31388. /**
  31389. * An event triggered before drawing the mesh
  31390. */
  31391. get: function () {
  31392. if (!this._onBeforeDrawObservable) {
  31393. this._onBeforeDrawObservable = new BABYLON.Observable();
  31394. }
  31395. return this._onBeforeDrawObservable;
  31396. },
  31397. enumerable: true,
  31398. configurable: true
  31399. });
  31400. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31401. set: function (callback) {
  31402. if (this._onBeforeDrawObserver) {
  31403. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31404. }
  31405. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31406. },
  31407. enumerable: true,
  31408. configurable: true
  31409. });
  31410. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31411. get: function () {
  31412. return this._morphTargetManager;
  31413. },
  31414. set: function (value) {
  31415. if (this._morphTargetManager === value) {
  31416. return;
  31417. }
  31418. this._morphTargetManager = value;
  31419. this._syncGeometryWithMorphTargetManager();
  31420. },
  31421. enumerable: true,
  31422. configurable: true
  31423. });
  31424. Object.defineProperty(Mesh.prototype, "source", {
  31425. get: function () {
  31426. return this._source;
  31427. },
  31428. enumerable: true,
  31429. configurable: true
  31430. });
  31431. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31432. get: function () {
  31433. return this._unIndexed;
  31434. },
  31435. set: function (value) {
  31436. if (this._unIndexed !== value) {
  31437. this._unIndexed = value;
  31438. this._markSubMeshesAsAttributesDirty();
  31439. }
  31440. },
  31441. enumerable: true,
  31442. configurable: true
  31443. });
  31444. // Methods
  31445. /**
  31446. * Returns the string "Mesh".
  31447. */
  31448. Mesh.prototype.getClassName = function () {
  31449. return "Mesh";
  31450. };
  31451. /**
  31452. * Returns a string.
  31453. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31454. */
  31455. Mesh.prototype.toString = function (fullDetails) {
  31456. var ret = _super.prototype.toString.call(this, fullDetails);
  31457. ret += ", n vertices: " + this.getTotalVertices();
  31458. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31459. if (this.animations) {
  31460. for (var i = 0; i < this.animations.length; i++) {
  31461. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31462. }
  31463. }
  31464. if (fullDetails) {
  31465. if (this._geometry) {
  31466. var ib = this.getIndices();
  31467. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31468. if (vb && ib) {
  31469. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31470. }
  31471. }
  31472. else {
  31473. ret += ", flat shading: UNKNOWN";
  31474. }
  31475. }
  31476. return ret;
  31477. };
  31478. /** @hidden */
  31479. Mesh.prototype._unBindEffect = function () {
  31480. _super.prototype._unBindEffect.call(this);
  31481. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31482. var instance = _a[_i];
  31483. instance._unBindEffect();
  31484. }
  31485. };
  31486. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31487. /**
  31488. * True if the mesh has some Levels Of Details (LOD).
  31489. * Returns a boolean.
  31490. */
  31491. get: function () {
  31492. return this._LODLevels.length > 0;
  31493. },
  31494. enumerable: true,
  31495. configurable: true
  31496. });
  31497. /**
  31498. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31499. * @returns an array of {BABYLON.MeshLODLevel}
  31500. */
  31501. Mesh.prototype.getLODLevels = function () {
  31502. return this._LODLevels;
  31503. };
  31504. Mesh.prototype._sortLODLevels = function () {
  31505. this._LODLevels.sort(function (a, b) {
  31506. if (a.distance < b.distance) {
  31507. return 1;
  31508. }
  31509. if (a.distance > b.distance) {
  31510. return -1;
  31511. }
  31512. return 0;
  31513. });
  31514. };
  31515. /**
  31516. * Add a mesh as LOD level triggered at the given distance.
  31517. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31518. * @param distance The distance from the center of the object to show this level
  31519. * @param mesh The mesh to be added as LOD level (can be null)
  31520. * @return This mesh (for chaining)
  31521. */
  31522. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31523. if (mesh && mesh._masterMesh) {
  31524. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31525. return this;
  31526. }
  31527. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31528. this._LODLevels.push(level);
  31529. if (mesh) {
  31530. mesh._masterMesh = this;
  31531. }
  31532. this._sortLODLevels();
  31533. return this;
  31534. };
  31535. /**
  31536. * Returns the LOD level mesh at the passed distance or null if not found.
  31537. * It is related to the method `addLODLevel(distance, mesh)`.
  31538. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31539. * Returns an object Mesh or `null`.
  31540. */
  31541. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31542. for (var index = 0; index < this._LODLevels.length; index++) {
  31543. var level = this._LODLevels[index];
  31544. if (level.distance === distance) {
  31545. return level.mesh;
  31546. }
  31547. }
  31548. return null;
  31549. };
  31550. /**
  31551. * Remove a mesh from the LOD array
  31552. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31553. * @param {Mesh} mesh The mesh to be removed.
  31554. * @return {Mesh} This mesh (for chaining)
  31555. */
  31556. Mesh.prototype.removeLODLevel = function (mesh) {
  31557. for (var index = 0; index < this._LODLevels.length; index++) {
  31558. if (this._LODLevels[index].mesh === mesh) {
  31559. this._LODLevels.splice(index, 1);
  31560. if (mesh) {
  31561. mesh._masterMesh = null;
  31562. }
  31563. }
  31564. }
  31565. this._sortLODLevels();
  31566. return this;
  31567. };
  31568. /**
  31569. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31570. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31571. */
  31572. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31573. if (!this._LODLevels || this._LODLevels.length === 0) {
  31574. return this;
  31575. }
  31576. var bSphere;
  31577. if (boundingSphere) {
  31578. bSphere = boundingSphere;
  31579. }
  31580. else {
  31581. var boundingInfo = this.getBoundingInfo();
  31582. bSphere = boundingInfo.boundingSphere;
  31583. }
  31584. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31585. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31586. if (this.onLODLevelSelection) {
  31587. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31588. }
  31589. return this;
  31590. }
  31591. for (var index = 0; index < this._LODLevels.length; index++) {
  31592. var level = this._LODLevels[index];
  31593. if (level.distance < distanceToCamera) {
  31594. if (level.mesh) {
  31595. level.mesh._preActivate();
  31596. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31597. }
  31598. if (this.onLODLevelSelection) {
  31599. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31600. }
  31601. return level.mesh;
  31602. }
  31603. }
  31604. if (this.onLODLevelSelection) {
  31605. this.onLODLevelSelection(distanceToCamera, this, this);
  31606. }
  31607. return this;
  31608. };
  31609. Object.defineProperty(Mesh.prototype, "geometry", {
  31610. /**
  31611. * Returns the mesh internal Geometry object.
  31612. */
  31613. get: function () {
  31614. return this._geometry;
  31615. },
  31616. enumerable: true,
  31617. configurable: true
  31618. });
  31619. /**
  31620. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31621. */
  31622. Mesh.prototype.getTotalVertices = function () {
  31623. if (this._geometry === null || this._geometry === undefined) {
  31624. return 0;
  31625. }
  31626. return this._geometry.getTotalVertices();
  31627. };
  31628. /**
  31629. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31630. * 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.
  31631. * You can force the copy with forceCopy === true
  31632. * Returns null if the mesh has no geometry or no vertex buffer.
  31633. * Possible `kind` values :
  31634. * - BABYLON.VertexBuffer.PositionKind
  31635. * - BABYLON.VertexBuffer.UVKind
  31636. * - BABYLON.VertexBuffer.UV2Kind
  31637. * - BABYLON.VertexBuffer.UV3Kind
  31638. * - BABYLON.VertexBuffer.UV4Kind
  31639. * - BABYLON.VertexBuffer.UV5Kind
  31640. * - BABYLON.VertexBuffer.UV6Kind
  31641. * - BABYLON.VertexBuffer.ColorKind
  31642. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31643. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31644. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31645. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31646. */
  31647. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31648. if (!this._geometry) {
  31649. return null;
  31650. }
  31651. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31652. };
  31653. /**
  31654. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31655. * Returns `null` if the mesh has no geometry.
  31656. * Possible `kind` values :
  31657. * - BABYLON.VertexBuffer.PositionKind
  31658. * - BABYLON.VertexBuffer.UVKind
  31659. * - BABYLON.VertexBuffer.UV2Kind
  31660. * - BABYLON.VertexBuffer.UV3Kind
  31661. * - BABYLON.VertexBuffer.UV4Kind
  31662. * - BABYLON.VertexBuffer.UV5Kind
  31663. * - BABYLON.VertexBuffer.UV6Kind
  31664. * - BABYLON.VertexBuffer.ColorKind
  31665. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31666. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31667. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31668. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31669. */
  31670. Mesh.prototype.getVertexBuffer = function (kind) {
  31671. if (!this._geometry) {
  31672. return null;
  31673. }
  31674. return this._geometry.getVertexBuffer(kind);
  31675. };
  31676. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31677. if (!this._geometry) {
  31678. if (this._delayInfo) {
  31679. return this._delayInfo.indexOf(kind) !== -1;
  31680. }
  31681. return false;
  31682. }
  31683. return this._geometry.isVerticesDataPresent(kind);
  31684. };
  31685. /**
  31686. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31687. * Possible `kind` values :
  31688. * - BABYLON.VertexBuffer.PositionKind
  31689. * - BABYLON.VertexBuffer.UVKind
  31690. * - BABYLON.VertexBuffer.UV2Kind
  31691. * - BABYLON.VertexBuffer.UV3Kind
  31692. * - BABYLON.VertexBuffer.UV4Kind
  31693. * - BABYLON.VertexBuffer.UV5Kind
  31694. * - BABYLON.VertexBuffer.UV6Kind
  31695. * - BABYLON.VertexBuffer.ColorKind
  31696. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31697. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31698. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31699. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31700. */
  31701. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31702. if (!this._geometry) {
  31703. if (this._delayInfo) {
  31704. return this._delayInfo.indexOf(kind) !== -1;
  31705. }
  31706. return false;
  31707. }
  31708. return this._geometry.isVertexBufferUpdatable(kind);
  31709. };
  31710. /**
  31711. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31712. * Possible `kind` values :
  31713. * - BABYLON.VertexBuffer.PositionKind
  31714. * - BABYLON.VertexBuffer.UVKind
  31715. * - BABYLON.VertexBuffer.UV2Kind
  31716. * - BABYLON.VertexBuffer.UV3Kind
  31717. * - BABYLON.VertexBuffer.UV4Kind
  31718. * - BABYLON.VertexBuffer.UV5Kind
  31719. * - BABYLON.VertexBuffer.UV6Kind
  31720. * - BABYLON.VertexBuffer.ColorKind
  31721. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31722. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31723. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31724. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31725. */
  31726. Mesh.prototype.getVerticesDataKinds = function () {
  31727. if (!this._geometry) {
  31728. var result = new Array();
  31729. if (this._delayInfo) {
  31730. this._delayInfo.forEach(function (kind, index, array) {
  31731. result.push(kind);
  31732. });
  31733. }
  31734. return result;
  31735. }
  31736. return this._geometry.getVerticesDataKinds();
  31737. };
  31738. /**
  31739. * Returns a positive integer : the total number of indices in this mesh geometry.
  31740. * Returns zero if the mesh has no geometry.
  31741. */
  31742. Mesh.prototype.getTotalIndices = function () {
  31743. if (!this._geometry) {
  31744. return 0;
  31745. }
  31746. return this._geometry.getTotalIndices();
  31747. };
  31748. /**
  31749. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31750. * @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.
  31751. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31752. * @returns the indices array or an empty array if the mesh has no geometry
  31753. */
  31754. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31755. if (!this._geometry) {
  31756. return [];
  31757. }
  31758. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31759. };
  31760. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31761. get: function () {
  31762. return this._masterMesh !== null && this._masterMesh !== undefined;
  31763. },
  31764. enumerable: true,
  31765. configurable: true
  31766. });
  31767. /**
  31768. * Determine if the current mesh is ready to be rendered
  31769. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31770. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31771. * @returns true if all associated assets are ready (material, textures, shaders)
  31772. */
  31773. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31774. if (completeCheck === void 0) { completeCheck = false; }
  31775. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31776. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31777. return false;
  31778. }
  31779. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31780. return false;
  31781. }
  31782. if (!this.subMeshes || this.subMeshes.length === 0) {
  31783. return true;
  31784. }
  31785. if (!completeCheck) {
  31786. return true;
  31787. }
  31788. var engine = this.getEngine();
  31789. var scene = this.getScene();
  31790. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31791. this.computeWorldMatrix();
  31792. var mat = this.material || scene.defaultMaterial;
  31793. if (mat) {
  31794. if (mat.storeEffectOnSubMeshes) {
  31795. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31796. var subMesh = _a[_i];
  31797. var effectiveMaterial = subMesh.getMaterial();
  31798. if (effectiveMaterial) {
  31799. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31800. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31801. return false;
  31802. }
  31803. }
  31804. else {
  31805. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31806. return false;
  31807. }
  31808. }
  31809. }
  31810. }
  31811. }
  31812. else {
  31813. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31814. return false;
  31815. }
  31816. }
  31817. }
  31818. // Shadows
  31819. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31820. var light = _c[_b];
  31821. var generator = light.getShadowGenerator();
  31822. if (generator) {
  31823. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31824. var subMesh = _e[_d];
  31825. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31826. return false;
  31827. }
  31828. }
  31829. }
  31830. }
  31831. // LOD
  31832. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31833. var lod = _g[_f];
  31834. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31835. return false;
  31836. }
  31837. }
  31838. return true;
  31839. };
  31840. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31841. /**
  31842. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31843. * This property is pertinent only for updatable parametric shapes.
  31844. */
  31845. get: function () {
  31846. return this._areNormalsFrozen;
  31847. },
  31848. enumerable: true,
  31849. configurable: true
  31850. });
  31851. /**
  31852. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31853. * It has no effect at all on other shapes.
  31854. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31855. * Returns the Mesh.
  31856. */
  31857. Mesh.prototype.freezeNormals = function () {
  31858. this._areNormalsFrozen = true;
  31859. return this;
  31860. };
  31861. /**
  31862. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31863. * It has no effect at all on other shapes.
  31864. * It reactivates the mesh normals computation if it was previously frozen.
  31865. * Returns the Mesh.
  31866. */
  31867. Mesh.prototype.unfreezeNormals = function () {
  31868. this._areNormalsFrozen = false;
  31869. return this;
  31870. };
  31871. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31872. /**
  31873. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31874. */
  31875. set: function (count) {
  31876. this._overridenInstanceCount = count;
  31877. },
  31878. enumerable: true,
  31879. configurable: true
  31880. });
  31881. // Methods
  31882. /** @hidden */
  31883. Mesh.prototype._preActivate = function () {
  31884. var sceneRenderId = this.getScene().getRenderId();
  31885. if (this._preActivateId === sceneRenderId) {
  31886. return this;
  31887. }
  31888. this._preActivateId = sceneRenderId;
  31889. this._visibleInstances = null;
  31890. return this;
  31891. };
  31892. /** @hidden */
  31893. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31894. if (this._visibleInstances) {
  31895. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31896. }
  31897. return this;
  31898. };
  31899. /** @hidden */
  31900. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31901. if (!this._visibleInstances) {
  31902. this._visibleInstances = {};
  31903. this._visibleInstances.defaultRenderId = renderId;
  31904. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31905. }
  31906. if (!this._visibleInstances[renderId]) {
  31907. this._visibleInstances[renderId] = new Array();
  31908. }
  31909. this._visibleInstances[renderId].push(instance);
  31910. return this;
  31911. };
  31912. /**
  31913. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31914. * This means the mesh underlying bounding box and sphere are recomputed.
  31915. * Returns the Mesh.
  31916. */
  31917. Mesh.prototype.refreshBoundingInfo = function () {
  31918. return this._refreshBoundingInfo(false);
  31919. };
  31920. /** @hidden */
  31921. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31922. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31923. return this;
  31924. }
  31925. var data = this._getPositionData(applySkeleton);
  31926. if (data) {
  31927. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31928. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31929. }
  31930. if (this.subMeshes) {
  31931. for (var index = 0; index < this.subMeshes.length; index++) {
  31932. this.subMeshes[index].refreshBoundingInfo();
  31933. }
  31934. }
  31935. this._updateBoundingInfo();
  31936. return this;
  31937. };
  31938. Mesh.prototype._getPositionData = function (applySkeleton) {
  31939. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31940. if (data && applySkeleton && this.skeleton) {
  31941. data = BABYLON.Tools.Slice(data);
  31942. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31943. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31944. if (matricesWeightsData && matricesIndicesData) {
  31945. var needExtras = this.numBoneInfluencers > 4;
  31946. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31947. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31948. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31949. var tempVector = BABYLON.Tmp.Vector3[0];
  31950. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31951. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31952. var matWeightIdx = 0;
  31953. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31954. finalMatrix.reset();
  31955. var inf;
  31956. var weight;
  31957. for (inf = 0; inf < 4; inf++) {
  31958. weight = matricesWeightsData[matWeightIdx + inf];
  31959. if (weight > 0) {
  31960. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31961. finalMatrix.addToSelf(tempMatrix);
  31962. }
  31963. }
  31964. if (needExtras) {
  31965. for (inf = 0; inf < 4; inf++) {
  31966. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31967. if (weight > 0) {
  31968. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31969. finalMatrix.addToSelf(tempMatrix);
  31970. }
  31971. }
  31972. }
  31973. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31974. tempVector.toArray(data, index);
  31975. }
  31976. }
  31977. }
  31978. return data;
  31979. };
  31980. /** @hidden */
  31981. Mesh.prototype._createGlobalSubMesh = function (force) {
  31982. var totalVertices = this.getTotalVertices();
  31983. if (!totalVertices || !this.getIndices()) {
  31984. return null;
  31985. }
  31986. // Check if we need to recreate the submeshes
  31987. if (this.subMeshes && this.subMeshes.length > 0) {
  31988. var ib = this.getIndices();
  31989. if (!ib) {
  31990. return null;
  31991. }
  31992. var totalIndices = ib.length;
  31993. var needToRecreate = false;
  31994. if (force) {
  31995. needToRecreate = true;
  31996. }
  31997. else {
  31998. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31999. var submesh = _a[_i];
  32000. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32001. needToRecreate = true;
  32002. break;
  32003. }
  32004. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32005. needToRecreate = true;
  32006. break;
  32007. }
  32008. }
  32009. }
  32010. if (!needToRecreate) {
  32011. return this.subMeshes[0];
  32012. }
  32013. }
  32014. this.releaseSubMeshes();
  32015. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32016. };
  32017. Mesh.prototype.subdivide = function (count) {
  32018. if (count < 1) {
  32019. return;
  32020. }
  32021. var totalIndices = this.getTotalIndices();
  32022. var subdivisionSize = (totalIndices / count) | 0;
  32023. var offset = 0;
  32024. // Ensure that subdivisionSize is a multiple of 3
  32025. while (subdivisionSize % 3 !== 0) {
  32026. subdivisionSize++;
  32027. }
  32028. this.releaseSubMeshes();
  32029. for (var index = 0; index < count; index++) {
  32030. if (offset >= totalIndices) {
  32031. break;
  32032. }
  32033. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32034. offset += subdivisionSize;
  32035. }
  32036. this.synchronizeInstances();
  32037. };
  32038. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32039. if (updatable === void 0) { updatable = false; }
  32040. if (!this._geometry) {
  32041. var vertexData = new BABYLON.VertexData();
  32042. vertexData.set(data, kind);
  32043. var scene = this.getScene();
  32044. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32045. }
  32046. else {
  32047. this._geometry.setVerticesData(kind, data, updatable, stride);
  32048. }
  32049. return this;
  32050. };
  32051. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32052. if (updatable === void 0) { updatable = true; }
  32053. var vb = this.getVertexBuffer(kind);
  32054. if (!vb || vb.isUpdatable() === updatable) {
  32055. return;
  32056. }
  32057. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32058. };
  32059. /**
  32060. * Sets the mesh VertexBuffer.
  32061. * Returns the Mesh.
  32062. */
  32063. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32064. if (!this._geometry) {
  32065. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32066. }
  32067. this._geometry.setVerticesBuffer(buffer);
  32068. return this;
  32069. };
  32070. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32071. if (!this._geometry) {
  32072. return this;
  32073. }
  32074. if (!makeItUnique) {
  32075. this._geometry.updateVerticesData(kind, data, updateExtends);
  32076. }
  32077. else {
  32078. this.makeGeometryUnique();
  32079. this.updateVerticesData(kind, data, updateExtends, false);
  32080. }
  32081. return this;
  32082. };
  32083. /**
  32084. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32085. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32086. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32087. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32088. * Returns the Mesh.
  32089. */
  32090. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32091. if (computeNormals === void 0) { computeNormals = true; }
  32092. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32093. if (!positions) {
  32094. return this;
  32095. }
  32096. positionFunction(positions);
  32097. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32098. if (computeNormals) {
  32099. var indices = this.getIndices();
  32100. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32101. if (!normals) {
  32102. return this;
  32103. }
  32104. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32105. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32106. }
  32107. return this;
  32108. };
  32109. /**
  32110. * Creates a un-shared specific occurence of the geometry for the mesh.
  32111. * Returns the Mesh.
  32112. */
  32113. Mesh.prototype.makeGeometryUnique = function () {
  32114. if (!this._geometry) {
  32115. return this;
  32116. }
  32117. var oldGeometry = this._geometry;
  32118. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32119. oldGeometry.releaseForMesh(this, true);
  32120. geometry.applyToMesh(this);
  32121. return this;
  32122. };
  32123. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32124. if (totalVertices === void 0) { totalVertices = null; }
  32125. if (updatable === void 0) { updatable = false; }
  32126. if (!this._geometry) {
  32127. var vertexData = new BABYLON.VertexData();
  32128. vertexData.indices = indices;
  32129. var scene = this.getScene();
  32130. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32131. }
  32132. else {
  32133. this._geometry.setIndices(indices, totalVertices, updatable);
  32134. }
  32135. return this;
  32136. };
  32137. /**
  32138. * Update the current index buffer
  32139. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32140. * Returns the Mesh.
  32141. */
  32142. Mesh.prototype.updateIndices = function (indices, offset) {
  32143. if (!this._geometry) {
  32144. return this;
  32145. }
  32146. this._geometry.updateIndices(indices, offset);
  32147. return this;
  32148. };
  32149. /**
  32150. * Invert the geometry to move from a right handed system to a left handed one.
  32151. * Returns the Mesh.
  32152. */
  32153. Mesh.prototype.toLeftHanded = function () {
  32154. if (!this._geometry) {
  32155. return this;
  32156. }
  32157. this._geometry.toLeftHanded();
  32158. return this;
  32159. };
  32160. /** @hidden */
  32161. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32162. if (!this._geometry) {
  32163. return this;
  32164. }
  32165. var engine = this.getScene().getEngine();
  32166. // Wireframe
  32167. var indexToBind;
  32168. if (this._unIndexed) {
  32169. indexToBind = null;
  32170. }
  32171. else {
  32172. switch (fillMode) {
  32173. case BABYLON.Material.PointFillMode:
  32174. indexToBind = null;
  32175. break;
  32176. case BABYLON.Material.WireFrameFillMode:
  32177. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32178. break;
  32179. default:
  32180. case BABYLON.Material.TriangleFillMode:
  32181. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32182. break;
  32183. }
  32184. }
  32185. // VBOs
  32186. this._geometry._bind(effect, indexToBind);
  32187. return this;
  32188. };
  32189. /** @hidden */
  32190. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32191. if (alternate === void 0) { alternate = false; }
  32192. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32193. return this;
  32194. }
  32195. if (this._onBeforeDrawObservable) {
  32196. this._onBeforeDrawObservable.notifyObservers(this);
  32197. }
  32198. var scene = this.getScene();
  32199. var engine = scene.getEngine();
  32200. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32201. // or triangles as points
  32202. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32203. }
  32204. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32205. // Triangles as wireframe
  32206. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32207. }
  32208. else {
  32209. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32210. }
  32211. if (scene._isAlternateRenderingEnabled && !alternate) {
  32212. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32213. if (!effect || !scene.activeCamera) {
  32214. return this;
  32215. }
  32216. scene._switchToAlternateCameraConfiguration(true);
  32217. this._effectiveMaterial.bindView(effect);
  32218. this._effectiveMaterial.bindViewProjection(effect);
  32219. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32220. this._draw(subMesh, fillMode, instancesCount, true);
  32221. engine.setViewport(scene.activeCamera.viewport);
  32222. scene._switchToAlternateCameraConfiguration(false);
  32223. this._effectiveMaterial.bindView(effect);
  32224. this._effectiveMaterial.bindViewProjection(effect);
  32225. }
  32226. return this;
  32227. };
  32228. /**
  32229. * Registers for this mesh a javascript function called just before the rendering process.
  32230. * This function is passed the current mesh.
  32231. * Return the Mesh.
  32232. */
  32233. Mesh.prototype.registerBeforeRender = function (func) {
  32234. this.onBeforeRenderObservable.add(func);
  32235. return this;
  32236. };
  32237. /**
  32238. * Disposes a previously registered javascript function called before the rendering.
  32239. * This function is passed the current mesh.
  32240. * Returns the Mesh.
  32241. */
  32242. Mesh.prototype.unregisterBeforeRender = function (func) {
  32243. this.onBeforeRenderObservable.removeCallback(func);
  32244. return this;
  32245. };
  32246. /**
  32247. * Registers for this mesh a javascript function called just after the rendering is complete.
  32248. * This function is passed the current mesh.
  32249. * Returns the Mesh.
  32250. */
  32251. Mesh.prototype.registerAfterRender = function (func) {
  32252. this.onAfterRenderObservable.add(func);
  32253. return this;
  32254. };
  32255. /**
  32256. * Disposes a previously registered javascript function called after the rendering.
  32257. * This function is passed the current mesh.
  32258. * Return the Mesh.
  32259. */
  32260. Mesh.prototype.unregisterAfterRender = function (func) {
  32261. this.onAfterRenderObservable.removeCallback(func);
  32262. return this;
  32263. };
  32264. /** @hidden */
  32265. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32266. var scene = this.getScene();
  32267. this._batchCache.mustReturn = false;
  32268. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32269. this._batchCache.visibleInstances[subMeshId] = null;
  32270. if (this._visibleInstances) {
  32271. var currentRenderId = scene.getRenderId();
  32272. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32273. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32274. var selfRenderId = this._renderId;
  32275. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32276. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32277. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32278. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32279. }
  32280. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32281. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32282. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32283. this._batchCache.mustReturn = true;
  32284. return this._batchCache;
  32285. }
  32286. if (currentRenderId !== selfRenderId) {
  32287. this._batchCache.renderSelf[subMeshId] = false;
  32288. }
  32289. }
  32290. this._renderIdForInstances[subMeshId] = currentRenderId;
  32291. }
  32292. return this._batchCache;
  32293. };
  32294. /** @hidden */
  32295. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32296. var visibleInstances = batch.visibleInstances[subMesh._id];
  32297. if (!visibleInstances) {
  32298. return this;
  32299. }
  32300. var matricesCount = visibleInstances.length + 1;
  32301. var bufferSize = matricesCount * 16 * 4;
  32302. var currentInstancesBufferSize = this._instancesBufferSize;
  32303. var instancesBuffer = this._instancesBuffer;
  32304. while (this._instancesBufferSize < bufferSize) {
  32305. this._instancesBufferSize *= 2;
  32306. }
  32307. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32308. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32309. }
  32310. var offset = 0;
  32311. var instancesCount = 0;
  32312. var world = this.getWorldMatrix();
  32313. if (batch.renderSelf[subMesh._id]) {
  32314. world.copyToArray(this._instancesData, offset);
  32315. offset += 16;
  32316. instancesCount++;
  32317. }
  32318. if (visibleInstances) {
  32319. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32320. var instance = visibleInstances[instanceIndex];
  32321. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32322. offset += 16;
  32323. instancesCount++;
  32324. }
  32325. }
  32326. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32327. if (instancesBuffer) {
  32328. instancesBuffer.dispose();
  32329. }
  32330. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32331. this._instancesBuffer = instancesBuffer;
  32332. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32333. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32334. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32335. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32336. }
  32337. else {
  32338. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32339. }
  32340. this._bind(subMesh, effect, fillMode);
  32341. this._draw(subMesh, fillMode, instancesCount);
  32342. engine.unbindInstanceAttributes();
  32343. return this;
  32344. };
  32345. /** @hidden */
  32346. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32347. var scene = this.getScene();
  32348. var engine = scene.getEngine();
  32349. if (hardwareInstancedRendering) {
  32350. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32351. }
  32352. else {
  32353. if (batch.renderSelf[subMesh._id]) {
  32354. // Draw
  32355. if (onBeforeDraw) {
  32356. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32357. }
  32358. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32359. }
  32360. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32361. if (visibleInstancesForSubMesh) {
  32362. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32363. var instance = visibleInstancesForSubMesh[instanceIndex];
  32364. // World
  32365. var world = instance.getWorldMatrix();
  32366. if (onBeforeDraw) {
  32367. onBeforeDraw(true, world, effectiveMaterial);
  32368. }
  32369. // Draw
  32370. this._draw(subMesh, fillMode);
  32371. }
  32372. }
  32373. }
  32374. return this;
  32375. };
  32376. /**
  32377. * 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
  32378. * @param subMesh defines the subMesh to render
  32379. * @param enableAlphaMode defines if alpha mode can be changed
  32380. * @returns the current mesh
  32381. */
  32382. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32383. this._checkOcclusionQuery();
  32384. if (this._isOccluded) {
  32385. return this;
  32386. }
  32387. var scene = this.getScene();
  32388. // Managing instances
  32389. var batch = this._getInstancesRenderList(subMesh._id);
  32390. if (batch.mustReturn) {
  32391. return this;
  32392. }
  32393. // Checking geometry state
  32394. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32395. return this;
  32396. }
  32397. if (this._onBeforeRenderObservable) {
  32398. this._onBeforeRenderObservable.notifyObservers(this);
  32399. }
  32400. var engine = scene.getEngine();
  32401. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32402. // Material
  32403. var material = subMesh.getMaterial();
  32404. if (!material) {
  32405. return this;
  32406. }
  32407. this._effectiveMaterial = material;
  32408. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32409. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32410. return this;
  32411. }
  32412. }
  32413. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32414. return this;
  32415. }
  32416. // Alpha mode
  32417. if (enableAlphaMode) {
  32418. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32419. }
  32420. // Outline - step 1
  32421. var savedDepthWrite = engine.getDepthWrite();
  32422. if (this.renderOutline) {
  32423. engine.setDepthWrite(false);
  32424. scene.getOutlineRenderer().render(subMesh, batch);
  32425. engine.setDepthWrite(savedDepthWrite);
  32426. }
  32427. var effect;
  32428. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32429. effect = subMesh.effect;
  32430. }
  32431. else {
  32432. effect = this._effectiveMaterial.getEffect();
  32433. }
  32434. if (!effect) {
  32435. return this;
  32436. }
  32437. var sideOrientation = this.overrideMaterialSideOrientation;
  32438. if (sideOrientation == null) {
  32439. sideOrientation = this._effectiveMaterial.sideOrientation;
  32440. if (this._getWorldMatrixDeterminant() < 0) {
  32441. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32442. }
  32443. }
  32444. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32445. if (this._effectiveMaterial.forceDepthWrite) {
  32446. engine.setDepthWrite(true);
  32447. }
  32448. // Bind
  32449. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32450. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32451. this._bind(subMesh, effect, fillMode);
  32452. }
  32453. var world = this.getWorldMatrix();
  32454. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32455. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32456. }
  32457. else {
  32458. this._effectiveMaterial.bind(world, this);
  32459. }
  32460. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32461. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32462. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32463. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32464. }
  32465. // Draw
  32466. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32467. // Unbind
  32468. this._effectiveMaterial.unbind();
  32469. // Outline - step 2
  32470. if (this.renderOutline && savedDepthWrite) {
  32471. engine.setDepthWrite(true);
  32472. engine.setColorWrite(false);
  32473. scene.getOutlineRenderer().render(subMesh, batch);
  32474. engine.setColorWrite(true);
  32475. }
  32476. // Overlay
  32477. if (this.renderOverlay) {
  32478. var currentMode = engine.getAlphaMode();
  32479. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32480. scene.getOutlineRenderer().render(subMesh, batch, true);
  32481. engine.setAlphaMode(currentMode);
  32482. }
  32483. if (this._onAfterRenderObservable) {
  32484. this._onAfterRenderObservable.notifyObservers(this);
  32485. }
  32486. return this;
  32487. };
  32488. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32489. if (isInstance && effectiveMaterial) {
  32490. effectiveMaterial.bindOnlyWorldMatrix(world);
  32491. }
  32492. };
  32493. /**
  32494. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32495. */
  32496. Mesh.prototype.getEmittedParticleSystems = function () {
  32497. var results = new Array();
  32498. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32499. var particleSystem = this.getScene().particleSystems[index];
  32500. if (particleSystem.emitter === this) {
  32501. results.push(particleSystem);
  32502. }
  32503. }
  32504. return results;
  32505. };
  32506. /**
  32507. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32508. */
  32509. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32510. var results = new Array();
  32511. var descendants = this.getDescendants();
  32512. descendants.push(this);
  32513. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32514. var particleSystem = this.getScene().particleSystems[index];
  32515. var emitter = particleSystem.emitter;
  32516. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32517. results.push(particleSystem);
  32518. }
  32519. }
  32520. return results;
  32521. };
  32522. /**
  32523. * Normalize matrix weights so that all vertices have a total weight set to 1
  32524. */
  32525. Mesh.prototype.cleanMatrixWeights = function () {
  32526. var epsilon = 1e-3;
  32527. var noInfluenceBoneIndex = 0.0;
  32528. if (this.skeleton) {
  32529. noInfluenceBoneIndex = this.skeleton.bones.length;
  32530. }
  32531. else {
  32532. return;
  32533. }
  32534. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32535. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32536. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32537. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32538. var influencers = this.numBoneInfluencers;
  32539. var size = matricesWeights.length;
  32540. for (var i = 0; i < size; i += 4) {
  32541. var weight = 0.0;
  32542. var firstZeroWeight = -1;
  32543. for (var j = 0; j < 4; j++) {
  32544. var w = matricesWeights[i + j];
  32545. weight += w;
  32546. if (w < epsilon && firstZeroWeight < 0) {
  32547. firstZeroWeight = j;
  32548. }
  32549. }
  32550. if (matricesWeightsExtra) {
  32551. for (var j = 0; j < 4; j++) {
  32552. var w = matricesWeightsExtra[i + j];
  32553. weight += w;
  32554. if (w < epsilon && firstZeroWeight < 0) {
  32555. firstZeroWeight = j + 4;
  32556. }
  32557. }
  32558. }
  32559. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32560. firstZeroWeight = influencers - 1;
  32561. }
  32562. if (weight > epsilon) {
  32563. var mweight = 1.0 / weight;
  32564. for (var j = 0; j < 4; j++) {
  32565. matricesWeights[i + j] *= mweight;
  32566. }
  32567. if (matricesWeightsExtra) {
  32568. for (var j = 0; j < 4; j++) {
  32569. matricesWeightsExtra[i + j] *= mweight;
  32570. }
  32571. }
  32572. }
  32573. else {
  32574. if (firstZeroWeight >= 4) {
  32575. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32576. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32577. }
  32578. else {
  32579. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32580. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32581. }
  32582. }
  32583. }
  32584. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32585. if (matricesIndicesExtra) {
  32586. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32587. }
  32588. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32589. if (matricesWeightsExtra) {
  32590. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32591. }
  32592. };
  32593. /** @hidden */
  32594. Mesh.prototype._checkDelayState = function () {
  32595. var scene = this.getScene();
  32596. if (this._geometry) {
  32597. this._geometry.load(scene);
  32598. }
  32599. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32600. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32601. this._queueLoad(scene);
  32602. }
  32603. return this;
  32604. };
  32605. Mesh.prototype._queueLoad = function (scene) {
  32606. var _this = this;
  32607. scene._addPendingData(this);
  32608. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32609. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32610. if (data instanceof ArrayBuffer) {
  32611. _this._delayLoadingFunction(data, _this);
  32612. }
  32613. else {
  32614. _this._delayLoadingFunction(JSON.parse(data), _this);
  32615. }
  32616. _this.instances.forEach(function (instance) {
  32617. instance._syncSubMeshes();
  32618. });
  32619. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32620. scene._removePendingData(_this);
  32621. }, function () { }, scene.database, getBinaryData);
  32622. return this;
  32623. };
  32624. /**
  32625. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  32626. * A mesh is in the frustum if its bounding box intersects the frustum
  32627. * @param frustumPlanes defines the frustum to test
  32628. * @returns true if the mesh is in the frustum planes
  32629. */
  32630. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32631. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32632. return false;
  32633. }
  32634. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32635. return false;
  32636. }
  32637. this._checkDelayState();
  32638. return true;
  32639. };
  32640. /**
  32641. * Sets the mesh material by the material or multiMaterial `id` property.
  32642. * The material `id` is a string identifying the material or the multiMaterial.
  32643. * This method returns the Mesh.
  32644. */
  32645. Mesh.prototype.setMaterialByID = function (id) {
  32646. var materials = this.getScene().materials;
  32647. var index;
  32648. for (index = materials.length - 1; index > -1; index--) {
  32649. if (materials[index].id === id) {
  32650. this.material = materials[index];
  32651. return this;
  32652. }
  32653. }
  32654. // Multi
  32655. var multiMaterials = this.getScene().multiMaterials;
  32656. for (index = multiMaterials.length - 1; index > -1; index--) {
  32657. if (multiMaterials[index].id === id) {
  32658. this.material = multiMaterials[index];
  32659. return this;
  32660. }
  32661. }
  32662. return this;
  32663. };
  32664. /**
  32665. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32666. */
  32667. Mesh.prototype.getAnimatables = function () {
  32668. var results = new Array();
  32669. if (this.material) {
  32670. results.push(this.material);
  32671. }
  32672. if (this.skeleton) {
  32673. results.push(this.skeleton);
  32674. }
  32675. return results;
  32676. };
  32677. /**
  32678. * Modifies the mesh geometry according to the passed transformation matrix.
  32679. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32680. * The mesh normals are modified using the same transformation.
  32681. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32682. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32683. * Returns the Mesh.
  32684. */
  32685. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32686. // Position
  32687. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32688. return this;
  32689. }
  32690. var submeshes = this.subMeshes.splice(0);
  32691. this._resetPointsArrayCache();
  32692. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32693. var temp = new Array();
  32694. var index;
  32695. for (index = 0; index < data.length; index += 3) {
  32696. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32697. }
  32698. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32699. // Normals
  32700. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32701. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32702. temp = [];
  32703. for (index = 0; index < data.length; index += 3) {
  32704. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32705. }
  32706. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32707. }
  32708. // flip faces?
  32709. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32710. this.flipFaces();
  32711. }
  32712. // Restore submeshes
  32713. this.releaseSubMeshes();
  32714. this.subMeshes = submeshes;
  32715. return this;
  32716. };
  32717. /**
  32718. * Modifies the mesh geometry according to its own current World Matrix.
  32719. * The mesh World Matrix is then reset.
  32720. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32721. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32722. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32723. * Returns the Mesh.
  32724. */
  32725. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32726. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32727. this.scaling.copyFromFloats(1, 1, 1);
  32728. this.position.copyFromFloats(0, 0, 0);
  32729. this.rotation.copyFromFloats(0, 0, 0);
  32730. //only if quaternion is already set
  32731. if (this.rotationQuaternion) {
  32732. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32733. }
  32734. this._worldMatrix = BABYLON.Matrix.Identity();
  32735. return this;
  32736. };
  32737. Object.defineProperty(Mesh.prototype, "_positions", {
  32738. // Cache
  32739. get: function () {
  32740. if (this._geometry) {
  32741. return this._geometry._positions;
  32742. }
  32743. return null;
  32744. },
  32745. enumerable: true,
  32746. configurable: true
  32747. });
  32748. /** @hidden */
  32749. Mesh.prototype._resetPointsArrayCache = function () {
  32750. if (this._geometry) {
  32751. this._geometry._resetPointsArrayCache();
  32752. }
  32753. return this;
  32754. };
  32755. /** @hidden */
  32756. Mesh.prototype._generatePointsArray = function () {
  32757. if (this._geometry) {
  32758. return this._geometry._generatePointsArray();
  32759. }
  32760. return false;
  32761. };
  32762. /**
  32763. * Returns a new Mesh object generated from the current mesh properties.
  32764. * This method must not get confused with createInstance().
  32765. * The parameter `name` is a string, the name given to the new mesh.
  32766. * The optional parameter `newParent` can be any Node object (default `null`).
  32767. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32768. * 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.
  32769. */
  32770. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32771. if (name === void 0) { name = ""; }
  32772. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32773. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32774. };
  32775. /**
  32776. * Releases resources associated with this mesh.
  32777. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32778. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32779. */
  32780. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32781. var _this = this;
  32782. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32783. this.morphTargetManager = null;
  32784. if (this._geometry) {
  32785. this._geometry.releaseForMesh(this, true);
  32786. }
  32787. if (this._onBeforeDrawObservable) {
  32788. this._onBeforeDrawObservable.clear();
  32789. }
  32790. if (this._onBeforeRenderObservable) {
  32791. this._onBeforeRenderObservable.clear();
  32792. }
  32793. if (this._onAfterRenderObservable) {
  32794. this._onAfterRenderObservable.clear();
  32795. }
  32796. // Sources
  32797. var meshes = this.getScene().meshes;
  32798. meshes.forEach(function (abstractMesh) {
  32799. var mesh = abstractMesh;
  32800. if (mesh._source && mesh._source === _this) {
  32801. mesh._source = null;
  32802. }
  32803. });
  32804. this._source = null;
  32805. // Instances
  32806. if (this._instancesBuffer) {
  32807. this._instancesBuffer.dispose();
  32808. this._instancesBuffer = null;
  32809. }
  32810. while (this.instances.length) {
  32811. this.instances[0].dispose();
  32812. }
  32813. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32814. };
  32815. /**
  32816. * Modifies the mesh geometry according to a displacement map.
  32817. * 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.
  32818. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32819. * This method returns nothing.
  32820. * @param url is a string, the URL from the image file is to be downloaded.
  32821. * @param minHeight is the lower limit of the displacement.
  32822. * @param maxHeight is the upper limit of the displacement.
  32823. * @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.
  32824. * @param uvOffset is an optional vector2 used to offset UV.
  32825. * @param uvScale is an optional vector2 used to scale UV.
  32826. * @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.
  32827. * @returns the Mesh.
  32828. */
  32829. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32830. var _this = this;
  32831. if (forceUpdate === void 0) { forceUpdate = false; }
  32832. var scene = this.getScene();
  32833. var onload = function (img) {
  32834. // Getting height map data
  32835. var canvas = document.createElement("canvas");
  32836. var context = canvas.getContext("2d");
  32837. var heightMapWidth = img.width;
  32838. var heightMapHeight = img.height;
  32839. canvas.width = heightMapWidth;
  32840. canvas.height = heightMapHeight;
  32841. context.drawImage(img, 0, 0);
  32842. // Create VertexData from map data
  32843. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32844. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32845. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32846. //execute success callback, if set
  32847. if (onSuccess) {
  32848. onSuccess(_this);
  32849. }
  32850. };
  32851. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32852. return this;
  32853. };
  32854. /**
  32855. * Modifies the mesh geometry according to a displacementMap buffer.
  32856. * 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.
  32857. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32858. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32859. * @param heightMapWidth is the width of the buffer image.
  32860. * @param heightMapHeight is the height of the buffer image.
  32861. * @param minHeight is the lower limit of the displacement.
  32862. * @param maxHeight is the upper limit of the displacement.
  32863. * @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.
  32864. * @param uvOffset is an optional vector2 used to offset UV.
  32865. * @param uvScale is an optional vector2 used to scale UV.
  32866. * @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.
  32867. * @returns the Mesh.
  32868. */
  32869. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32870. if (forceUpdate === void 0) { forceUpdate = false; }
  32871. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32872. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32873. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32874. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32875. return this;
  32876. }
  32877. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32878. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32879. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32880. var position = BABYLON.Vector3.Zero();
  32881. var normal = BABYLON.Vector3.Zero();
  32882. var uv = BABYLON.Vector2.Zero();
  32883. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32884. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32885. for (var index = 0; index < positions.length; index += 3) {
  32886. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32887. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32888. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32889. // Compute height
  32890. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32891. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32892. var pos = (u + v * heightMapWidth) * 4;
  32893. var r = buffer[pos] / 255.0;
  32894. var g = buffer[pos + 1] / 255.0;
  32895. var b = buffer[pos + 2] / 255.0;
  32896. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32897. normal.normalize();
  32898. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32899. position = position.add(normal);
  32900. position.toArray(positions, index);
  32901. }
  32902. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32903. if (forceUpdate) {
  32904. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32905. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32906. }
  32907. else {
  32908. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32909. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32910. }
  32911. return this;
  32912. };
  32913. /**
  32914. * Modify the mesh to get a flat shading rendering.
  32915. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32916. * This method returns the Mesh.
  32917. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32918. */
  32919. Mesh.prototype.convertToFlatShadedMesh = function () {
  32920. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32921. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32922. var kinds = this.getVerticesDataKinds();
  32923. var vbs = {};
  32924. var data = {};
  32925. var newdata = {};
  32926. var updatableNormals = false;
  32927. var kindIndex;
  32928. var kind;
  32929. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32930. kind = kinds[kindIndex];
  32931. var vertexBuffer = this.getVertexBuffer(kind);
  32932. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32933. updatableNormals = vertexBuffer.isUpdatable();
  32934. kinds.splice(kindIndex, 1);
  32935. kindIndex--;
  32936. continue;
  32937. }
  32938. vbs[kind] = vertexBuffer;
  32939. data[kind] = vbs[kind].getData();
  32940. newdata[kind] = [];
  32941. }
  32942. // Save previous submeshes
  32943. var previousSubmeshes = this.subMeshes.slice(0);
  32944. var indices = this.getIndices();
  32945. var totalIndices = this.getTotalIndices();
  32946. // Generating unique vertices per face
  32947. var index;
  32948. for (index = 0; index < totalIndices; index++) {
  32949. var vertexIndex = indices[index];
  32950. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32951. kind = kinds[kindIndex];
  32952. var stride = vbs[kind].getStrideSize();
  32953. for (var offset = 0; offset < stride; offset++) {
  32954. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32955. }
  32956. }
  32957. }
  32958. // Updating faces & normal
  32959. var normals = [];
  32960. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32961. for (index = 0; index < totalIndices; index += 3) {
  32962. indices[index] = index;
  32963. indices[index + 1] = index + 1;
  32964. indices[index + 2] = index + 2;
  32965. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32966. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32967. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32968. var p1p2 = p1.subtract(p2);
  32969. var p3p2 = p3.subtract(p2);
  32970. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32971. // Store same normals for every vertex
  32972. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32973. normals.push(normal.x);
  32974. normals.push(normal.y);
  32975. normals.push(normal.z);
  32976. }
  32977. }
  32978. this.setIndices(indices);
  32979. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32980. // Updating vertex buffers
  32981. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32982. kind = kinds[kindIndex];
  32983. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32984. }
  32985. // Updating submeshes
  32986. this.releaseSubMeshes();
  32987. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32988. var previousOne = previousSubmeshes[submeshIndex];
  32989. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32990. }
  32991. this.synchronizeInstances();
  32992. return this;
  32993. };
  32994. /**
  32995. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32996. * In other words, more vertices, no more indices and a single bigger VBO.
  32997. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32998. * Returns the Mesh.
  32999. */
  33000. Mesh.prototype.convertToUnIndexedMesh = function () {
  33001. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33002. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33003. var kinds = this.getVerticesDataKinds();
  33004. var vbs = {};
  33005. var data = {};
  33006. var newdata = {};
  33007. var kindIndex;
  33008. var kind;
  33009. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33010. kind = kinds[kindIndex];
  33011. var vertexBuffer = this.getVertexBuffer(kind);
  33012. vbs[kind] = vertexBuffer;
  33013. data[kind] = vbs[kind].getData();
  33014. newdata[kind] = [];
  33015. }
  33016. // Save previous submeshes
  33017. var previousSubmeshes = this.subMeshes.slice(0);
  33018. var indices = this.getIndices();
  33019. var totalIndices = this.getTotalIndices();
  33020. // Generating unique vertices per face
  33021. var index;
  33022. for (index = 0; index < totalIndices; index++) {
  33023. var vertexIndex = indices[index];
  33024. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33025. kind = kinds[kindIndex];
  33026. var stride = vbs[kind].getStrideSize();
  33027. for (var offset = 0; offset < stride; offset++) {
  33028. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33029. }
  33030. }
  33031. }
  33032. // Updating indices
  33033. for (index = 0; index < totalIndices; index += 3) {
  33034. indices[index] = index;
  33035. indices[index + 1] = index + 1;
  33036. indices[index + 2] = index + 2;
  33037. }
  33038. this.setIndices(indices);
  33039. // Updating vertex buffers
  33040. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33041. kind = kinds[kindIndex];
  33042. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33043. }
  33044. // Updating submeshes
  33045. this.releaseSubMeshes();
  33046. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33047. var previousOne = previousSubmeshes[submeshIndex];
  33048. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33049. }
  33050. this._unIndexed = true;
  33051. this.synchronizeInstances();
  33052. return this;
  33053. };
  33054. /**
  33055. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33056. * This method returns the Mesh.
  33057. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33058. */
  33059. Mesh.prototype.flipFaces = function (flipNormals) {
  33060. if (flipNormals === void 0) { flipNormals = false; }
  33061. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33062. var i;
  33063. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33064. for (i = 0; i < vertex_data.normals.length; i++) {
  33065. vertex_data.normals[i] *= -1;
  33066. }
  33067. }
  33068. if (vertex_data.indices) {
  33069. var temp;
  33070. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33071. // reassign indices
  33072. temp = vertex_data.indices[i + 1];
  33073. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33074. vertex_data.indices[i + 2] = temp;
  33075. }
  33076. }
  33077. vertex_data.applyToMesh(this);
  33078. return this;
  33079. };
  33080. // Instances
  33081. /**
  33082. * Creates a new InstancedMesh object from the mesh model.
  33083. * An instance shares the same properties and the same material than its model.
  33084. * Please make sure to call mesh.makeGeometryUnique() if you are calling createInstance on a previously cloned mesh.
  33085. * Only these properties of each instance can then be set individually :
  33086. * - position
  33087. * - rotation
  33088. * - rotationQuaternion
  33089. * - setPivotMatrix
  33090. * - scaling
  33091. *
  33092. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  33093. * Warning : this method is not supported for Line mesh and LineSystem
  33094. */
  33095. Mesh.prototype.createInstance = function (name) {
  33096. return new BABYLON.InstancedMesh(name, this);
  33097. };
  33098. /**
  33099. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33100. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33101. * This method returns the Mesh.
  33102. */
  33103. Mesh.prototype.synchronizeInstances = function () {
  33104. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33105. var instance = this.instances[instanceIndex];
  33106. instance._syncSubMeshes();
  33107. }
  33108. return this;
  33109. };
  33110. /**
  33111. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33112. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33113. * This should be used together with the simplification to avoid disappearing triangles.
  33114. * Returns the Mesh.
  33115. * @param successCallback an optional success callback to be called after the optimization finished.
  33116. */
  33117. Mesh.prototype.optimizeIndices = function (successCallback) {
  33118. var _this = this;
  33119. var indices = this.getIndices();
  33120. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33121. if (!positions || !indices) {
  33122. return this;
  33123. }
  33124. var vectorPositions = new Array();
  33125. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33126. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33127. }
  33128. var dupes = new Array();
  33129. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33130. var realPos = vectorPositions.length - 1 - iteration;
  33131. var testedPosition = vectorPositions[realPos];
  33132. for (var j = 0; j < realPos; ++j) {
  33133. var againstPosition = vectorPositions[j];
  33134. if (testedPosition.equals(againstPosition)) {
  33135. dupes[realPos] = j;
  33136. break;
  33137. }
  33138. }
  33139. }, function () {
  33140. for (var i = 0; i < indices.length; ++i) {
  33141. indices[i] = dupes[indices[i]] || indices[i];
  33142. }
  33143. //indices are now reordered
  33144. var originalSubMeshes = _this.subMeshes.slice(0);
  33145. _this.setIndices(indices);
  33146. _this.subMeshes = originalSubMeshes;
  33147. if (successCallback) {
  33148. successCallback(_this);
  33149. }
  33150. });
  33151. return this;
  33152. };
  33153. Mesh.prototype.serialize = function (serializationObject) {
  33154. serializationObject.name = this.name;
  33155. serializationObject.id = this.id;
  33156. serializationObject.type = this.getClassName();
  33157. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33158. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33159. }
  33160. serializationObject.position = this.position.asArray();
  33161. if (this.rotationQuaternion) {
  33162. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33163. }
  33164. else if (this.rotation) {
  33165. serializationObject.rotation = this.rotation.asArray();
  33166. }
  33167. serializationObject.scaling = this.scaling.asArray();
  33168. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33169. serializationObject.isEnabled = this.isEnabled(false);
  33170. serializationObject.isVisible = this.isVisible;
  33171. serializationObject.infiniteDistance = this.infiniteDistance;
  33172. serializationObject.pickable = this.isPickable;
  33173. serializationObject.receiveShadows = this.receiveShadows;
  33174. serializationObject.billboardMode = this.billboardMode;
  33175. serializationObject.visibility = this.visibility;
  33176. serializationObject.checkCollisions = this.checkCollisions;
  33177. serializationObject.isBlocker = this.isBlocker;
  33178. // Parent
  33179. if (this.parent) {
  33180. serializationObject.parentId = this.parent.id;
  33181. }
  33182. // Geometry
  33183. serializationObject.isUnIndexed = this.isUnIndexed;
  33184. var geometry = this._geometry;
  33185. if (geometry) {
  33186. var geometryId = geometry.id;
  33187. serializationObject.geometryId = geometryId;
  33188. // SubMeshes
  33189. serializationObject.subMeshes = [];
  33190. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33191. var subMesh = this.subMeshes[subIndex];
  33192. serializationObject.subMeshes.push({
  33193. materialIndex: subMesh.materialIndex,
  33194. verticesStart: subMesh.verticesStart,
  33195. verticesCount: subMesh.verticesCount,
  33196. indexStart: subMesh.indexStart,
  33197. indexCount: subMesh.indexCount
  33198. });
  33199. }
  33200. }
  33201. // Material
  33202. if (this.material) {
  33203. serializationObject.materialId = this.material.id;
  33204. }
  33205. else {
  33206. this.material = null;
  33207. }
  33208. // Morph targets
  33209. if (this.morphTargetManager) {
  33210. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33211. }
  33212. // Skeleton
  33213. if (this.skeleton) {
  33214. serializationObject.skeletonId = this.skeleton.id;
  33215. }
  33216. // Physics
  33217. //TODO implement correct serialization for physics impostors.
  33218. var impostor = this.getPhysicsImpostor();
  33219. if (impostor) {
  33220. serializationObject.physicsMass = impostor.getParam("mass");
  33221. serializationObject.physicsFriction = impostor.getParam("friction");
  33222. serializationObject.physicsRestitution = impostor.getParam("mass");
  33223. serializationObject.physicsImpostor = impostor.type;
  33224. }
  33225. // Metadata
  33226. if (this.metadata) {
  33227. serializationObject.metadata = this.metadata;
  33228. }
  33229. // Instances
  33230. serializationObject.instances = [];
  33231. for (var index = 0; index < this.instances.length; index++) {
  33232. var instance = this.instances[index];
  33233. if (instance.doNotSerialize) {
  33234. continue;
  33235. }
  33236. var serializationInstance = {
  33237. name: instance.name,
  33238. id: instance.id,
  33239. position: instance.position.asArray(),
  33240. scaling: instance.scaling.asArray()
  33241. };
  33242. if (instance.parent) {
  33243. serializationInstance.parentId = instance.parent.id;
  33244. }
  33245. if (instance.rotationQuaternion) {
  33246. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33247. }
  33248. else if (instance.rotation) {
  33249. serializationInstance.rotation = instance.rotation.asArray();
  33250. }
  33251. serializationObject.instances.push(serializationInstance);
  33252. // Animations
  33253. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33254. serializationInstance.ranges = instance.serializeAnimationRanges();
  33255. }
  33256. //
  33257. // Animations
  33258. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33259. serializationObject.ranges = this.serializeAnimationRanges();
  33260. // Layer mask
  33261. serializationObject.layerMask = this.layerMask;
  33262. // Alpha
  33263. serializationObject.alphaIndex = this.alphaIndex;
  33264. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33265. // Overlay
  33266. serializationObject.overlayAlpha = this.overlayAlpha;
  33267. serializationObject.overlayColor = this.overlayColor.asArray();
  33268. serializationObject.renderOverlay = this.renderOverlay;
  33269. // Fog
  33270. serializationObject.applyFog = this.applyFog;
  33271. // Action Manager
  33272. if (this.actionManager) {
  33273. serializationObject.actions = this.actionManager.serialize(this.name);
  33274. }
  33275. };
  33276. /** @hidden */
  33277. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33278. if (!this.geometry) {
  33279. return;
  33280. }
  33281. this._markSubMeshesAsAttributesDirty();
  33282. var morphTargetManager = this._morphTargetManager;
  33283. if (morphTargetManager && morphTargetManager.vertexCount) {
  33284. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33285. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33286. this.morphTargetManager = null;
  33287. return;
  33288. }
  33289. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33290. var morphTarget = morphTargetManager.getActiveTarget(index);
  33291. var positions = morphTarget.getPositions();
  33292. if (!positions) {
  33293. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33294. return;
  33295. }
  33296. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33297. var normals = morphTarget.getNormals();
  33298. if (normals) {
  33299. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33300. }
  33301. var tangents = morphTarget.getTangents();
  33302. if (tangents) {
  33303. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33304. }
  33305. }
  33306. }
  33307. else {
  33308. var index = 0;
  33309. // Positions
  33310. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33311. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33312. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33313. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33314. }
  33315. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33316. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33317. }
  33318. index++;
  33319. }
  33320. }
  33321. };
  33322. // Statics
  33323. /**
  33324. * Returns a new Mesh object parsed from the source provided.
  33325. * The parameter `parsedMesh` is the source.
  33326. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33327. */
  33328. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33329. var mesh;
  33330. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33331. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33332. }
  33333. else {
  33334. mesh = new Mesh(parsedMesh.name, scene);
  33335. }
  33336. mesh.id = parsedMesh.id;
  33337. if (BABYLON.Tags) {
  33338. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33339. }
  33340. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33341. if (parsedMesh.metadata !== undefined) {
  33342. mesh.metadata = parsedMesh.metadata;
  33343. }
  33344. if (parsedMesh.rotationQuaternion) {
  33345. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33346. }
  33347. else if (parsedMesh.rotation) {
  33348. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33349. }
  33350. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33351. if (parsedMesh.localMatrix) {
  33352. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33353. }
  33354. else if (parsedMesh.pivotMatrix) {
  33355. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33356. }
  33357. mesh.setEnabled(parsedMesh.isEnabled);
  33358. mesh.isVisible = parsedMesh.isVisible;
  33359. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33360. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33361. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33362. if (parsedMesh.applyFog !== undefined) {
  33363. mesh.applyFog = parsedMesh.applyFog;
  33364. }
  33365. if (parsedMesh.pickable !== undefined) {
  33366. mesh.isPickable = parsedMesh.pickable;
  33367. }
  33368. if (parsedMesh.alphaIndex !== undefined) {
  33369. mesh.alphaIndex = parsedMesh.alphaIndex;
  33370. }
  33371. mesh.receiveShadows = parsedMesh.receiveShadows;
  33372. mesh.billboardMode = parsedMesh.billboardMode;
  33373. if (parsedMesh.visibility !== undefined) {
  33374. mesh.visibility = parsedMesh.visibility;
  33375. }
  33376. mesh.checkCollisions = parsedMesh.checkCollisions;
  33377. if (parsedMesh.isBlocker !== undefined) {
  33378. mesh.isBlocker = parsedMesh.isBlocker;
  33379. }
  33380. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33381. // freezeWorldMatrix
  33382. if (parsedMesh.freezeWorldMatrix) {
  33383. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33384. }
  33385. // Parent
  33386. if (parsedMesh.parentId) {
  33387. mesh._waitingParentId = parsedMesh.parentId;
  33388. }
  33389. // Actions
  33390. if (parsedMesh.actions !== undefined) {
  33391. mesh._waitingActions = parsedMesh.actions;
  33392. }
  33393. // Overlay
  33394. if (parsedMesh.overlayAlpha !== undefined) {
  33395. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33396. }
  33397. if (parsedMesh.overlayColor !== undefined) {
  33398. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33399. }
  33400. if (parsedMesh.renderOverlay !== undefined) {
  33401. mesh.renderOverlay = parsedMesh.renderOverlay;
  33402. }
  33403. // Geometry
  33404. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33405. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33406. if (parsedMesh.delayLoadingFile) {
  33407. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33408. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33409. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33410. if (parsedMesh._binaryInfo) {
  33411. mesh._binaryInfo = parsedMesh._binaryInfo;
  33412. }
  33413. mesh._delayInfo = [];
  33414. if (parsedMesh.hasUVs) {
  33415. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33416. }
  33417. if (parsedMesh.hasUVs2) {
  33418. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33419. }
  33420. if (parsedMesh.hasUVs3) {
  33421. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33422. }
  33423. if (parsedMesh.hasUVs4) {
  33424. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33425. }
  33426. if (parsedMesh.hasUVs5) {
  33427. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33428. }
  33429. if (parsedMesh.hasUVs6) {
  33430. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33431. }
  33432. if (parsedMesh.hasColors) {
  33433. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33434. }
  33435. if (parsedMesh.hasMatricesIndices) {
  33436. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33437. }
  33438. if (parsedMesh.hasMatricesWeights) {
  33439. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33440. }
  33441. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33442. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33443. mesh._checkDelayState();
  33444. }
  33445. }
  33446. else {
  33447. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33448. }
  33449. // Material
  33450. if (parsedMesh.materialId) {
  33451. mesh.setMaterialByID(parsedMesh.materialId);
  33452. }
  33453. else {
  33454. mesh.material = null;
  33455. }
  33456. // Morph targets
  33457. if (parsedMesh.morphTargetManagerId > -1) {
  33458. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33459. }
  33460. // Skeleton
  33461. if (parsedMesh.skeletonId > -1) {
  33462. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33463. if (parsedMesh.numBoneInfluencers) {
  33464. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33465. }
  33466. }
  33467. // Animations
  33468. if (parsedMesh.animations) {
  33469. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33470. var parsedAnimation = parsedMesh.animations[animationIndex];
  33471. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33472. }
  33473. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33474. }
  33475. if (parsedMesh.autoAnimate) {
  33476. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33477. }
  33478. // Layer Mask
  33479. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33480. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33481. }
  33482. else {
  33483. mesh.layerMask = 0x0FFFFFFF;
  33484. }
  33485. // Physics
  33486. if (parsedMesh.physicsImpostor) {
  33487. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33488. mass: parsedMesh.physicsMass,
  33489. friction: parsedMesh.physicsFriction,
  33490. restitution: parsedMesh.physicsRestitution
  33491. }, scene);
  33492. }
  33493. // Instances
  33494. if (parsedMesh.instances) {
  33495. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33496. var parsedInstance = parsedMesh.instances[index];
  33497. var instance = mesh.createInstance(parsedInstance.name);
  33498. if (parsedInstance.id) {
  33499. instance.id = parsedInstance.id;
  33500. }
  33501. if (BABYLON.Tags) {
  33502. if (parsedInstance.tags) {
  33503. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33504. }
  33505. else {
  33506. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  33507. }
  33508. }
  33509. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33510. if (parsedInstance.parentId) {
  33511. instance._waitingParentId = parsedInstance.parentId;
  33512. }
  33513. if (parsedInstance.rotationQuaternion) {
  33514. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33515. }
  33516. else if (parsedInstance.rotation) {
  33517. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33518. }
  33519. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33520. instance.checkCollisions = mesh.checkCollisions;
  33521. if (parsedMesh.animations) {
  33522. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33523. parsedAnimation = parsedMesh.animations[animationIndex];
  33524. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33525. }
  33526. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33527. if (parsedMesh.autoAnimate) {
  33528. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33529. }
  33530. }
  33531. }
  33532. }
  33533. return mesh;
  33534. };
  33535. /**
  33536. * Creates a ribbon mesh.
  33537. * Please consider using the same method from the MeshBuilder class instead.
  33538. * 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.
  33539. *
  33540. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33541. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33542. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33543. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33544. * 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.
  33545. * 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.
  33546. * 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
  33547. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33548. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33549. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33550. */
  33551. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33552. if (closeArray === void 0) { closeArray = false; }
  33553. if (updatable === void 0) { updatable = false; }
  33554. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33555. pathArray: pathArray,
  33556. closeArray: closeArray,
  33557. closePath: closePath,
  33558. offset: offset,
  33559. updatable: updatable,
  33560. sideOrientation: sideOrientation,
  33561. instance: instance
  33562. }, scene);
  33563. };
  33564. /**
  33565. * Creates a plane polygonal mesh. By default, this is a disc.
  33566. * Please consider using the same method from the MeshBuilder class instead.
  33567. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33568. * 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.
  33569. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33570. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33571. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33572. */
  33573. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33574. if (scene === void 0) { scene = null; }
  33575. var options = {
  33576. radius: radius,
  33577. tessellation: tessellation,
  33578. sideOrientation: sideOrientation,
  33579. updatable: updatable
  33580. };
  33581. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33582. };
  33583. /**
  33584. * Creates a box mesh.
  33585. * Please consider using the same method from the MeshBuilder class instead.
  33586. * The parameter `size` sets the size (float) of each box side (default 1).
  33587. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33588. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33589. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33590. */
  33591. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33592. if (scene === void 0) { scene = null; }
  33593. var options = {
  33594. size: size,
  33595. sideOrientation: sideOrientation,
  33596. updatable: updatable
  33597. };
  33598. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33599. };
  33600. /**
  33601. * Creates a sphere mesh.
  33602. * Please consider using the same method from the MeshBuilder class instead.
  33603. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33604. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33605. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33606. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33607. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33608. */
  33609. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33610. var options = {
  33611. segments: segments,
  33612. diameterX: diameter,
  33613. diameterY: diameter,
  33614. diameterZ: diameter,
  33615. sideOrientation: sideOrientation,
  33616. updatable: updatable
  33617. };
  33618. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33619. };
  33620. /**
  33621. * Creates a cylinder or a cone mesh.
  33622. * Please consider using the same method from the MeshBuilder class instead.
  33623. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33624. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33625. * 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.
  33626. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33627. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33628. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33629. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33630. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33631. */
  33632. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33633. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33634. if (scene !== undefined) {
  33635. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33636. updatable = scene;
  33637. }
  33638. scene = subdivisions;
  33639. subdivisions = 1;
  33640. }
  33641. var options = {
  33642. height: height,
  33643. diameterTop: diameterTop,
  33644. diameterBottom: diameterBottom,
  33645. tessellation: tessellation,
  33646. subdivisions: subdivisions,
  33647. sideOrientation: sideOrientation,
  33648. updatable: updatable
  33649. };
  33650. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33651. };
  33652. // Torus (Code from SharpDX.org)
  33653. /**
  33654. * Creates a torus mesh.
  33655. * Please consider using the same method from the MeshBuilder class instead.
  33656. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33657. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33658. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33659. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33660. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33661. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33662. */
  33663. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33664. var options = {
  33665. diameter: diameter,
  33666. thickness: thickness,
  33667. tessellation: tessellation,
  33668. sideOrientation: sideOrientation,
  33669. updatable: updatable
  33670. };
  33671. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33672. };
  33673. /**
  33674. * Creates a torus knot mesh.
  33675. * Please consider using the same method from the MeshBuilder class instead.
  33676. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33677. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33678. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33679. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33680. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33681. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33682. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33683. */
  33684. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33685. var options = {
  33686. radius: radius,
  33687. tube: tube,
  33688. radialSegments: radialSegments,
  33689. tubularSegments: tubularSegments,
  33690. p: p,
  33691. q: q,
  33692. sideOrientation: sideOrientation,
  33693. updatable: updatable
  33694. };
  33695. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33696. };
  33697. /**
  33698. * Creates a line mesh.
  33699. * Please consider using the same method from the MeshBuilder class instead.
  33700. * 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.
  33701. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33702. * The parameter `points` is an array successive Vector3.
  33703. * 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
  33704. * When updating an instance, remember that only point positions can change, not the number of points.
  33705. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33706. */
  33707. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33708. if (scene === void 0) { scene = null; }
  33709. if (updatable === void 0) { updatable = false; }
  33710. if (instance === void 0) { instance = null; }
  33711. var options = {
  33712. points: points,
  33713. updatable: updatable,
  33714. instance: instance
  33715. };
  33716. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33717. };
  33718. /**
  33719. * Creates a dashed line mesh.
  33720. * Please consider using the same method from the MeshBuilder class instead.
  33721. * 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.
  33722. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33723. * The parameter `points` is an array successive Vector3.
  33724. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33725. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33726. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33727. * 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
  33728. * When updating an instance, remember that only point positions can change, not the number of points.
  33729. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33730. */
  33731. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33732. if (scene === void 0) { scene = null; }
  33733. var options = {
  33734. points: points,
  33735. dashSize: dashSize,
  33736. gapSize: gapSize,
  33737. dashNb: dashNb,
  33738. updatable: updatable,
  33739. instance: instance
  33740. };
  33741. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33742. };
  33743. /**
  33744. * Creates a polygon mesh.
  33745. * Please consider using the same method from the MeshBuilder class instead.
  33746. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33747. * 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.
  33748. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33749. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33750. * Remember you can only change the shape positions, not their number when updating a polygon.
  33751. */
  33752. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33753. var options = {
  33754. shape: shape,
  33755. holes: holes,
  33756. updatable: updatable,
  33757. sideOrientation: sideOrientation
  33758. };
  33759. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33760. };
  33761. /**
  33762. * Creates an extruded polygon mesh, with depth in the Y direction.
  33763. * Please consider using the same method from the MeshBuilder class instead.
  33764. */
  33765. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33766. var options = {
  33767. shape: shape,
  33768. holes: holes,
  33769. depth: depth,
  33770. updatable: updatable,
  33771. sideOrientation: sideOrientation
  33772. };
  33773. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33774. };
  33775. /**
  33776. * Creates an extruded shape mesh.
  33777. * 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.
  33778. * Please consider using the same method from the MeshBuilder class instead.
  33779. *
  33780. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33781. * 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
  33782. * extruded along the Z axis.
  33783. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33784. * 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.
  33785. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33786. * 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
  33787. * 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
  33788. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33789. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33790. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33791. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33792. */
  33793. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33794. if (scene === void 0) { scene = null; }
  33795. var options = {
  33796. shape: shape,
  33797. path: path,
  33798. scale: scale,
  33799. rotation: rotation,
  33800. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33801. sideOrientation: sideOrientation,
  33802. instance: instance,
  33803. updatable: updatable
  33804. };
  33805. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33806. };
  33807. /**
  33808. * Creates an custom extruded shape mesh.
  33809. * 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.
  33810. * Please consider using the same method from the MeshBuilder class instead.
  33811. *
  33812. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33813. * 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
  33814. * extruded along the Z axis.
  33815. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33816. * 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
  33817. * and the distance of this point from the begining of the path :
  33818. * ```javascript
  33819. * var rotationFunction = function(i, distance) {
  33820. * // do things
  33821. * return rotationValue; }
  33822. * ```
  33823. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33824. * 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
  33825. * and the distance of this point from the begining of the path :
  33826. * ```javascript
  33827. * var scaleFunction = function(i, distance) {
  33828. * // do things
  33829. * return scaleValue;}
  33830. * ```
  33831. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33832. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33833. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33834. * 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
  33835. * 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
  33836. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33837. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33838. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33839. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33840. */
  33841. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33842. var options = {
  33843. shape: shape,
  33844. path: path,
  33845. scaleFunction: scaleFunction,
  33846. rotationFunction: rotationFunction,
  33847. ribbonCloseArray: ribbonCloseArray,
  33848. ribbonClosePath: ribbonClosePath,
  33849. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33850. sideOrientation: sideOrientation,
  33851. instance: instance,
  33852. updatable: updatable
  33853. };
  33854. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33855. };
  33856. /**
  33857. * Creates lathe mesh.
  33858. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33859. * Please consider using the same method from the MeshBuilder class instead.
  33860. * 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
  33861. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33862. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33863. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33864. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33865. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33866. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33867. */
  33868. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33869. var options = {
  33870. shape: shape,
  33871. radius: radius,
  33872. tessellation: tessellation,
  33873. sideOrientation: sideOrientation,
  33874. updatable: updatable
  33875. };
  33876. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33877. };
  33878. /**
  33879. * Creates a plane mesh.
  33880. * Please consider using the same method from the MeshBuilder class instead.
  33881. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33882. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33883. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33884. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33885. */
  33886. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33887. var options = {
  33888. size: size,
  33889. width: size,
  33890. height: size,
  33891. sideOrientation: sideOrientation,
  33892. updatable: updatable
  33893. };
  33894. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33895. };
  33896. /**
  33897. * Creates a ground mesh.
  33898. * Please consider using the same method from the MeshBuilder class instead.
  33899. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33900. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33901. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33902. */
  33903. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33904. var options = {
  33905. width: width,
  33906. height: height,
  33907. subdivisions: subdivisions,
  33908. updatable: updatable
  33909. };
  33910. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33911. };
  33912. /**
  33913. * Creates a tiled ground mesh.
  33914. * Please consider using the same method from the MeshBuilder class instead.
  33915. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33916. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33917. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33918. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33919. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33920. * numbers of subdivisions on the ground width and height of each tile.
  33921. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33922. */
  33923. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33924. var options = {
  33925. xmin: xmin,
  33926. zmin: zmin,
  33927. xmax: xmax,
  33928. zmax: zmax,
  33929. subdivisions: subdivisions,
  33930. precision: precision,
  33931. updatable: updatable
  33932. };
  33933. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33934. };
  33935. /**
  33936. * Creates a ground mesh from a height map.
  33937. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33938. * Please consider using the same method from the MeshBuilder class instead.
  33939. * The parameter `url` sets the URL of the height map image resource.
  33940. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33941. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33942. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33943. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33944. * 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).
  33945. * This function is passed the newly built mesh :
  33946. * ```javascript
  33947. * function(mesh) { // do things
  33948. * return; }
  33949. * ```
  33950. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33951. */
  33952. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33953. var options = {
  33954. width: width,
  33955. height: height,
  33956. subdivisions: subdivisions,
  33957. minHeight: minHeight,
  33958. maxHeight: maxHeight,
  33959. updatable: updatable,
  33960. onReady: onReady
  33961. };
  33962. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33963. };
  33964. /**
  33965. * Creates a tube mesh.
  33966. * 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.
  33967. * Please consider using the same method from the MeshBuilder class instead.
  33968. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33969. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33970. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33971. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33972. * 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.
  33973. * It must return a radius value (positive float) :
  33974. * ```javascript
  33975. * var radiusFunction = function(i, distance) {
  33976. * // do things
  33977. * return radius; }
  33978. * ```
  33979. * 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
  33980. * 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
  33981. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33982. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33983. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33984. */
  33985. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33986. var options = {
  33987. path: path,
  33988. radius: radius,
  33989. tessellation: tessellation,
  33990. radiusFunction: radiusFunction,
  33991. arc: 1,
  33992. cap: cap,
  33993. updatable: updatable,
  33994. sideOrientation: sideOrientation,
  33995. instance: instance
  33996. };
  33997. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33998. };
  33999. /**
  34000. * Creates a polyhedron mesh.
  34001. * Please consider using the same method from the MeshBuilder class instead.
  34002. * 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
  34003. * to choose the wanted type.
  34004. * The parameter `size` (positive float, default 1) sets the polygon size.
  34005. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34006. * 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`.
  34007. * 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
  34008. * 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)`).
  34009. * 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
  34010. * 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.
  34011. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34012. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34013. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34014. */
  34015. Mesh.CreatePolyhedron = function (name, options, scene) {
  34016. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34017. };
  34018. /**
  34019. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34020. * Please consider using the same method from the MeshBuilder class instead.
  34021. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34022. * 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`).
  34023. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34024. * 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.
  34025. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34026. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34027. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34028. */
  34029. Mesh.CreateIcoSphere = function (name, options, scene) {
  34030. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34031. };
  34032. /**
  34033. * Creates a decal mesh.
  34034. * Please consider using the same method from the MeshBuilder class instead.
  34035. * 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.
  34036. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34037. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34038. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34039. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34040. */
  34041. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34042. var options = {
  34043. position: position,
  34044. normal: normal,
  34045. size: size,
  34046. angle: angle
  34047. };
  34048. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34049. };
  34050. // Skeletons
  34051. /**
  34052. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34053. */
  34054. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34055. if (!this._sourcePositions) {
  34056. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34057. if (!source) {
  34058. return this._sourcePositions;
  34059. }
  34060. this._sourcePositions = new Float32Array(source);
  34061. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34062. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34063. }
  34064. }
  34065. return this._sourcePositions;
  34066. };
  34067. /**
  34068. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34069. */
  34070. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34071. if (!this._sourceNormals) {
  34072. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34073. if (!source) {
  34074. return this._sourceNormals;
  34075. }
  34076. this._sourceNormals = new Float32Array(source);
  34077. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34078. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34079. }
  34080. }
  34081. return this._sourceNormals;
  34082. };
  34083. /**
  34084. * Updates the vertex buffer by applying transformation from the bones.
  34085. * Returns the Mesh.
  34086. *
  34087. * @param {skeleton} skeleton to apply
  34088. */
  34089. Mesh.prototype.applySkeleton = function (skeleton) {
  34090. if (!this.geometry) {
  34091. return this;
  34092. }
  34093. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34094. return this;
  34095. }
  34096. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34097. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34098. return this;
  34099. }
  34100. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34101. return this;
  34102. }
  34103. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34104. return this;
  34105. }
  34106. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34107. return this;
  34108. }
  34109. if (!this._sourcePositions) {
  34110. var submeshes = this.subMeshes.slice();
  34111. this.setPositionsForCPUSkinning();
  34112. this.subMeshes = submeshes;
  34113. }
  34114. if (!this._sourceNormals) {
  34115. this.setNormalsForCPUSkinning();
  34116. }
  34117. // positionsData checks for not being Float32Array will only pass at most once
  34118. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34119. if (!positionsData) {
  34120. return this;
  34121. }
  34122. if (!(positionsData instanceof Float32Array)) {
  34123. positionsData = new Float32Array(positionsData);
  34124. }
  34125. // normalsData checks for not being Float32Array will only pass at most once
  34126. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34127. if (!normalsData) {
  34128. return this;
  34129. }
  34130. if (!(normalsData instanceof Float32Array)) {
  34131. normalsData = new Float32Array(normalsData);
  34132. }
  34133. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34134. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34135. if (!matricesWeightsData || !matricesIndicesData) {
  34136. return this;
  34137. }
  34138. var needExtras = this.numBoneInfluencers > 4;
  34139. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34140. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34141. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34142. var tempVector3 = BABYLON.Vector3.Zero();
  34143. var finalMatrix = new BABYLON.Matrix();
  34144. var tempMatrix = new BABYLON.Matrix();
  34145. var matWeightIdx = 0;
  34146. var inf;
  34147. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34148. var weight;
  34149. for (inf = 0; inf < 4; inf++) {
  34150. weight = matricesWeightsData[matWeightIdx + inf];
  34151. if (weight > 0) {
  34152. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34153. finalMatrix.addToSelf(tempMatrix);
  34154. }
  34155. }
  34156. if (needExtras) {
  34157. for (inf = 0; inf < 4; inf++) {
  34158. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34159. if (weight > 0) {
  34160. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34161. finalMatrix.addToSelf(tempMatrix);
  34162. }
  34163. }
  34164. }
  34165. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34166. tempVector3.toArray(positionsData, index);
  34167. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34168. tempVector3.toArray(normalsData, index);
  34169. finalMatrix.reset();
  34170. }
  34171. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34172. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34173. return this;
  34174. };
  34175. // Tools
  34176. /**
  34177. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34178. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34179. */
  34180. Mesh.MinMax = function (meshes) {
  34181. var minVector = null;
  34182. var maxVector = null;
  34183. meshes.forEach(function (mesh, index, array) {
  34184. var boundingInfo = mesh.getBoundingInfo();
  34185. var boundingBox = boundingInfo.boundingBox;
  34186. if (!minVector || !maxVector) {
  34187. minVector = boundingBox.minimumWorld;
  34188. maxVector = boundingBox.maximumWorld;
  34189. }
  34190. else {
  34191. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34192. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34193. }
  34194. });
  34195. if (!minVector || !maxVector) {
  34196. return {
  34197. min: BABYLON.Vector3.Zero(),
  34198. max: BABYLON.Vector3.Zero()
  34199. };
  34200. }
  34201. return {
  34202. min: minVector,
  34203. max: maxVector
  34204. };
  34205. };
  34206. /**
  34207. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34208. */
  34209. Mesh.Center = function (meshesOrMinMaxVector) {
  34210. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34211. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34212. };
  34213. /**
  34214. * Merge the array of meshes into a single mesh for performance reasons.
  34215. * @param meshes - The vertices source. They should all be of the same material. Entries can empty
  34216. * @param disposeSource - When true (default), dispose of the vertices from the source meshes
  34217. * @param allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34218. * @param meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34219. * @param subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34220. */
  34221. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34222. if (disposeSource === void 0) { disposeSource = true; }
  34223. var index;
  34224. if (!allow32BitsIndices) {
  34225. var totalVertices = 0;
  34226. // Counting vertices
  34227. for (index = 0; index < meshes.length; index++) {
  34228. if (meshes[index]) {
  34229. totalVertices += meshes[index].getTotalVertices();
  34230. if (totalVertices > 65536) {
  34231. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34232. return null;
  34233. }
  34234. }
  34235. }
  34236. }
  34237. // Merge
  34238. var vertexData = null;
  34239. var otherVertexData;
  34240. var indiceArray = new Array();
  34241. var source = null;
  34242. for (index = 0; index < meshes.length; index++) {
  34243. if (meshes[index]) {
  34244. var wm = meshes[index].computeWorldMatrix(true);
  34245. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34246. otherVertexData.transform(wm);
  34247. if (vertexData) {
  34248. vertexData.merge(otherVertexData, allow32BitsIndices);
  34249. }
  34250. else {
  34251. vertexData = otherVertexData;
  34252. source = meshes[index];
  34253. }
  34254. if (subdivideWithSubMeshes) {
  34255. indiceArray.push(meshes[index].getTotalIndices());
  34256. }
  34257. }
  34258. }
  34259. source = source;
  34260. if (!meshSubclass) {
  34261. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34262. }
  34263. vertexData.applyToMesh(meshSubclass);
  34264. // Setting properties
  34265. meshSubclass.material = source.material;
  34266. meshSubclass.checkCollisions = source.checkCollisions;
  34267. // Cleaning
  34268. if (disposeSource) {
  34269. for (index = 0; index < meshes.length; index++) {
  34270. if (meshes[index]) {
  34271. meshes[index].dispose();
  34272. }
  34273. }
  34274. }
  34275. // Subdivide
  34276. if (subdivideWithSubMeshes) {
  34277. //-- removal of global submesh
  34278. meshSubclass.releaseSubMeshes();
  34279. index = 0;
  34280. var offset = 0;
  34281. //-- apply subdivision according to index table
  34282. while (index < indiceArray.length) {
  34283. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34284. offset += indiceArray[index];
  34285. index++;
  34286. }
  34287. }
  34288. return meshSubclass;
  34289. };
  34290. // Consts
  34291. Mesh._FRONTSIDE = 0;
  34292. Mesh._BACKSIDE = 1;
  34293. Mesh._DOUBLESIDE = 2;
  34294. Mesh._DEFAULTSIDE = 0;
  34295. Mesh._NO_CAP = 0;
  34296. Mesh._CAP_START = 1;
  34297. Mesh._CAP_END = 2;
  34298. Mesh._CAP_ALL = 3;
  34299. return Mesh;
  34300. }(BABYLON.AbstractMesh));
  34301. BABYLON.Mesh = Mesh;
  34302. })(BABYLON || (BABYLON = {}));
  34303. //# sourceMappingURL=babylon.mesh.js.map
  34304. var BABYLON;
  34305. (function (BABYLON) {
  34306. var BaseSubMesh = /** @class */ (function () {
  34307. function BaseSubMesh() {
  34308. }
  34309. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34310. get: function () {
  34311. return this._materialEffect;
  34312. },
  34313. enumerable: true,
  34314. configurable: true
  34315. });
  34316. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34317. if (defines === void 0) { defines = null; }
  34318. if (this._materialEffect === effect) {
  34319. if (!effect) {
  34320. this._materialDefines = null;
  34321. }
  34322. return;
  34323. }
  34324. this._materialDefines = defines;
  34325. this._materialEffect = effect;
  34326. };
  34327. return BaseSubMesh;
  34328. }());
  34329. BABYLON.BaseSubMesh = BaseSubMesh;
  34330. var SubMesh = /** @class */ (function (_super) {
  34331. __extends(SubMesh, _super);
  34332. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34333. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34334. var _this = _super.call(this) || this;
  34335. _this.materialIndex = materialIndex;
  34336. _this.verticesStart = verticesStart;
  34337. _this.verticesCount = verticesCount;
  34338. _this.indexStart = indexStart;
  34339. _this.indexCount = indexCount;
  34340. /** @hidden */
  34341. _this._renderId = 0;
  34342. _this._mesh = mesh;
  34343. _this._renderingMesh = renderingMesh || mesh;
  34344. mesh.subMeshes.push(_this);
  34345. _this._trianglePlanes = [];
  34346. _this._id = mesh.subMeshes.length - 1;
  34347. if (createBoundingBox) {
  34348. _this.refreshBoundingInfo();
  34349. mesh.computeWorldMatrix(true);
  34350. }
  34351. return _this;
  34352. }
  34353. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34354. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34355. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34356. };
  34357. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34358. get: function () {
  34359. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34360. },
  34361. enumerable: true,
  34362. configurable: true
  34363. });
  34364. /**
  34365. * Returns the submesh BoudingInfo object.
  34366. */
  34367. SubMesh.prototype.getBoundingInfo = function () {
  34368. if (this.IsGlobal) {
  34369. return this._mesh.getBoundingInfo();
  34370. }
  34371. return this._boundingInfo;
  34372. };
  34373. /**
  34374. * Sets the submesh BoundingInfo.
  34375. * Return the SubMesh.
  34376. */
  34377. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34378. this._boundingInfo = boundingInfo;
  34379. return this;
  34380. };
  34381. /**
  34382. * Returns the mesh of the current submesh.
  34383. */
  34384. SubMesh.prototype.getMesh = function () {
  34385. return this._mesh;
  34386. };
  34387. /**
  34388. * Returns the rendering mesh of the submesh.
  34389. */
  34390. SubMesh.prototype.getRenderingMesh = function () {
  34391. return this._renderingMesh;
  34392. };
  34393. /**
  34394. * Returns the submesh material.
  34395. */
  34396. SubMesh.prototype.getMaterial = function () {
  34397. var rootMaterial = this._renderingMesh.material;
  34398. if (rootMaterial === null || rootMaterial === undefined) {
  34399. return this._mesh.getScene().defaultMaterial;
  34400. }
  34401. else if (rootMaterial.getSubMaterial) {
  34402. var multiMaterial = rootMaterial;
  34403. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34404. if (this._currentMaterial !== effectiveMaterial) {
  34405. this._currentMaterial = effectiveMaterial;
  34406. this._materialDefines = null;
  34407. }
  34408. return effectiveMaterial;
  34409. }
  34410. return rootMaterial;
  34411. };
  34412. // Methods
  34413. /**
  34414. * Sets a new updated BoundingInfo object to the submesh.
  34415. * Returns the SubMesh.
  34416. */
  34417. SubMesh.prototype.refreshBoundingInfo = function () {
  34418. this._lastColliderWorldVertices = null;
  34419. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34420. return this;
  34421. }
  34422. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34423. if (!data) {
  34424. this._boundingInfo = this._mesh.getBoundingInfo();
  34425. return this;
  34426. }
  34427. var indices = this._renderingMesh.getIndices();
  34428. var extend;
  34429. //is this the only submesh?
  34430. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34431. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34432. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34433. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34434. }
  34435. else {
  34436. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34437. }
  34438. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34439. return this;
  34440. };
  34441. /** @hidden */
  34442. SubMesh.prototype._checkCollision = function (collider) {
  34443. var boundingInfo = this.getBoundingInfo();
  34444. return boundingInfo._checkCollision(collider);
  34445. };
  34446. /**
  34447. * Updates the submesh BoundingInfo.
  34448. * Returns the Submesh.
  34449. */
  34450. SubMesh.prototype.updateBoundingInfo = function (world) {
  34451. var boundingInfo = this.getBoundingInfo();
  34452. if (!boundingInfo) {
  34453. this.refreshBoundingInfo();
  34454. boundingInfo = this.getBoundingInfo();
  34455. }
  34456. boundingInfo.update(world);
  34457. return this;
  34458. };
  34459. /**
  34460. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34461. * Boolean returned.
  34462. */
  34463. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34464. var boundingInfo = this.getBoundingInfo();
  34465. if (!boundingInfo) {
  34466. return false;
  34467. }
  34468. return boundingInfo.isInFrustum(frustumPlanes);
  34469. };
  34470. /**
  34471. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34472. * Boolean returned.
  34473. */
  34474. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34475. var boundingInfo = this.getBoundingInfo();
  34476. if (!boundingInfo) {
  34477. return false;
  34478. }
  34479. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34480. };
  34481. /**
  34482. * Renders the submesh.
  34483. * Returns it.
  34484. */
  34485. SubMesh.prototype.render = function (enableAlphaMode) {
  34486. this._renderingMesh.render(this, enableAlphaMode);
  34487. return this;
  34488. };
  34489. /**
  34490. * Returns a new Index Buffer.
  34491. * Type returned : WebGLBuffer.
  34492. */
  34493. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34494. if (!this._linesIndexBuffer) {
  34495. var linesIndices = [];
  34496. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34497. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34498. }
  34499. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34500. this.linesIndexCount = linesIndices.length;
  34501. }
  34502. return this._linesIndexBuffer;
  34503. };
  34504. /**
  34505. * True is the passed Ray intersects the submesh bounding box.
  34506. * Boolean returned.
  34507. */
  34508. SubMesh.prototype.canIntersects = function (ray) {
  34509. var boundingInfo = this.getBoundingInfo();
  34510. if (!boundingInfo) {
  34511. return false;
  34512. }
  34513. return ray.intersectsBox(boundingInfo.boundingBox);
  34514. };
  34515. /**
  34516. * Returns an object IntersectionInfo.
  34517. */
  34518. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34519. var intersectInfo = null;
  34520. var material = this.getMaterial();
  34521. if (!material) {
  34522. return null;
  34523. }
  34524. switch (material.fillMode) {
  34525. case BABYLON.Material.PointListDrawMode:
  34526. case BABYLON.Material.LineListDrawMode:
  34527. case BABYLON.Material.LineLoopDrawMode:
  34528. case BABYLON.Material.LineStripDrawMode:
  34529. case BABYLON.Material.TriangleFanDrawMode:
  34530. case BABYLON.Material.TriangleStripDrawMode:
  34531. return null;
  34532. }
  34533. // LineMesh first as it's also a Mesh...
  34534. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34535. var lineMesh = this._mesh;
  34536. // Line test
  34537. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34538. var p0 = positions[indices[index]];
  34539. var p1 = positions[indices[index + 1]];
  34540. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34541. if (length < 0) {
  34542. continue;
  34543. }
  34544. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34545. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34546. if (fastCheck) {
  34547. break;
  34548. }
  34549. }
  34550. }
  34551. }
  34552. else {
  34553. // Triangles test
  34554. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34555. var p0 = positions[indices[index]];
  34556. var p1 = positions[indices[index + 1]];
  34557. var p2 = positions[indices[index + 2]];
  34558. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34559. if (currentIntersectInfo) {
  34560. if (currentIntersectInfo.distance < 0) {
  34561. continue;
  34562. }
  34563. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34564. intersectInfo = currentIntersectInfo;
  34565. intersectInfo.faceId = index / 3;
  34566. if (fastCheck) {
  34567. break;
  34568. }
  34569. }
  34570. }
  34571. }
  34572. }
  34573. return intersectInfo;
  34574. };
  34575. /** @hidden */
  34576. SubMesh.prototype._rebuild = function () {
  34577. if (this._linesIndexBuffer) {
  34578. this._linesIndexBuffer = null;
  34579. }
  34580. };
  34581. // Clone
  34582. /**
  34583. * Creates a new Submesh from the passed Mesh.
  34584. */
  34585. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34586. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34587. if (!this.IsGlobal) {
  34588. var boundingInfo = this.getBoundingInfo();
  34589. if (!boundingInfo) {
  34590. return result;
  34591. }
  34592. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34593. }
  34594. return result;
  34595. };
  34596. // Dispose
  34597. /**
  34598. * Disposes the Submesh.
  34599. * Returns nothing.
  34600. */
  34601. SubMesh.prototype.dispose = function () {
  34602. if (this._linesIndexBuffer) {
  34603. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34604. this._linesIndexBuffer = null;
  34605. }
  34606. // Remove from mesh
  34607. var index = this._mesh.subMeshes.indexOf(this);
  34608. this._mesh.subMeshes.splice(index, 1);
  34609. };
  34610. // Statics
  34611. /**
  34612. * Creates a new Submesh from the passed parameters :
  34613. * - materialIndex (integer) : the index of the main mesh material.
  34614. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34615. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34616. * - mesh (Mesh) : the main mesh to create the submesh from.
  34617. * - renderingMesh (optional Mesh) : rendering mesh.
  34618. */
  34619. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34620. var minVertexIndex = Number.MAX_VALUE;
  34621. var maxVertexIndex = -Number.MAX_VALUE;
  34622. renderingMesh = (renderingMesh || mesh);
  34623. var indices = renderingMesh.getIndices();
  34624. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34625. var vertexIndex = indices[index];
  34626. if (vertexIndex < minVertexIndex)
  34627. minVertexIndex = vertexIndex;
  34628. if (vertexIndex > maxVertexIndex)
  34629. maxVertexIndex = vertexIndex;
  34630. }
  34631. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34632. };
  34633. return SubMesh;
  34634. }(BaseSubMesh));
  34635. BABYLON.SubMesh = SubMesh;
  34636. })(BABYLON || (BABYLON = {}));
  34637. //# sourceMappingURL=babylon.subMesh.js.map
  34638. var __assign = (this && this.__assign) || function () {
  34639. __assign = Object.assign || function(t) {
  34640. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34641. s = arguments[i];
  34642. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34643. t[p] = s[p];
  34644. }
  34645. return t;
  34646. };
  34647. return __assign.apply(this, arguments);
  34648. };
  34649. var BABYLON;
  34650. (function (BABYLON) {
  34651. /**
  34652. * Manages the defines for the Material
  34653. */
  34654. var MaterialDefines = /** @class */ (function () {
  34655. function MaterialDefines() {
  34656. this._isDirty = true;
  34657. /** @hidden */
  34658. this._areLightsDirty = true;
  34659. /** @hidden */
  34660. this._areAttributesDirty = true;
  34661. /** @hidden */
  34662. this._areTexturesDirty = true;
  34663. /** @hidden */
  34664. this._areFresnelDirty = true;
  34665. /** @hidden */
  34666. this._areMiscDirty = true;
  34667. /** @hidden */
  34668. this._areImageProcessingDirty = true;
  34669. /** @hidden */
  34670. this._normals = false;
  34671. /** @hidden */
  34672. this._uvs = false;
  34673. /** @hidden */
  34674. this._needNormals = false;
  34675. /** @hidden */
  34676. this._needUVs = false;
  34677. }
  34678. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34679. /**
  34680. * Specifies if the material needs to be re-calculated
  34681. */
  34682. get: function () {
  34683. return this._isDirty;
  34684. },
  34685. enumerable: true,
  34686. configurable: true
  34687. });
  34688. /**
  34689. * Marks the material to indicate that it has been re-calculated
  34690. */
  34691. MaterialDefines.prototype.markAsProcessed = function () {
  34692. this._isDirty = false;
  34693. this._areAttributesDirty = false;
  34694. this._areTexturesDirty = false;
  34695. this._areFresnelDirty = false;
  34696. this._areLightsDirty = false;
  34697. this._areMiscDirty = false;
  34698. this._areImageProcessingDirty = false;
  34699. };
  34700. /**
  34701. * Marks the material to indicate that it needs to be re-calculated
  34702. */
  34703. MaterialDefines.prototype.markAsUnprocessed = function () {
  34704. this._isDirty = true;
  34705. };
  34706. /**
  34707. * Marks the material to indicate all of its defines need to be re-calculated
  34708. */
  34709. MaterialDefines.prototype.markAllAsDirty = function () {
  34710. this._areTexturesDirty = true;
  34711. this._areAttributesDirty = true;
  34712. this._areLightsDirty = true;
  34713. this._areFresnelDirty = true;
  34714. this._areMiscDirty = true;
  34715. this._areImageProcessingDirty = true;
  34716. this._isDirty = true;
  34717. };
  34718. /**
  34719. * Marks the material to indicate that image processing needs to be re-calculated
  34720. */
  34721. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34722. this._areImageProcessingDirty = true;
  34723. this._isDirty = true;
  34724. };
  34725. /**
  34726. * Marks the material to indicate the lights need to be re-calculated
  34727. */
  34728. MaterialDefines.prototype.markAsLightDirty = function () {
  34729. this._areLightsDirty = true;
  34730. this._isDirty = true;
  34731. };
  34732. /**
  34733. * Marks the attribute state as changed
  34734. */
  34735. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34736. this._areAttributesDirty = true;
  34737. this._isDirty = true;
  34738. };
  34739. /**
  34740. * Marks the texture state as changed
  34741. */
  34742. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34743. this._areTexturesDirty = true;
  34744. this._isDirty = true;
  34745. };
  34746. /**
  34747. * Marks the fresnel state as changed
  34748. */
  34749. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34750. this._areFresnelDirty = true;
  34751. this._isDirty = true;
  34752. };
  34753. /**
  34754. * Marks the misc state as changed
  34755. */
  34756. MaterialDefines.prototype.markAsMiscDirty = function () {
  34757. this._areMiscDirty = true;
  34758. this._isDirty = true;
  34759. };
  34760. /**
  34761. * Rebuilds the material defines
  34762. */
  34763. MaterialDefines.prototype.rebuild = function () {
  34764. if (this._keys) {
  34765. delete this._keys;
  34766. }
  34767. this._keys = [];
  34768. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34769. var key = _a[_i];
  34770. if (key[0] === "_") {
  34771. continue;
  34772. }
  34773. this._keys.push(key);
  34774. }
  34775. };
  34776. /**
  34777. * Specifies if two material defines are equal
  34778. * @param other - A material define instance to compare to
  34779. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34780. */
  34781. MaterialDefines.prototype.isEqual = function (other) {
  34782. if (this._keys.length !== other._keys.length) {
  34783. return false;
  34784. }
  34785. for (var index = 0; index < this._keys.length; index++) {
  34786. var prop = this._keys[index];
  34787. if (this[prop] !== other[prop]) {
  34788. return false;
  34789. }
  34790. }
  34791. return true;
  34792. };
  34793. /**
  34794. * Clones this instance's defines to another instance
  34795. * @param other - material defines to clone values to
  34796. */
  34797. MaterialDefines.prototype.cloneTo = function (other) {
  34798. if (this._keys.length !== other._keys.length) {
  34799. other._keys = this._keys.slice(0);
  34800. }
  34801. for (var index = 0; index < this._keys.length; index++) {
  34802. var prop = this._keys[index];
  34803. other[prop] = this[prop];
  34804. }
  34805. };
  34806. /**
  34807. * Resets the material define values
  34808. */
  34809. MaterialDefines.prototype.reset = function () {
  34810. for (var index = 0; index < this._keys.length; index++) {
  34811. var prop = this._keys[index];
  34812. var type = typeof this[prop];
  34813. switch (type) {
  34814. case "number":
  34815. this[prop] = 0;
  34816. break;
  34817. case "string":
  34818. this[prop] = "";
  34819. break;
  34820. default:
  34821. this[prop] = false;
  34822. break;
  34823. }
  34824. }
  34825. };
  34826. /**
  34827. * Converts the material define values to a string
  34828. * @returns - String of material define information
  34829. */
  34830. MaterialDefines.prototype.toString = function () {
  34831. var result = "";
  34832. for (var index = 0; index < this._keys.length; index++) {
  34833. var prop = this._keys[index];
  34834. var value = this[prop];
  34835. var type = typeof value;
  34836. switch (type) {
  34837. case "number":
  34838. case "string":
  34839. result += "#define " + prop + " " + value + "\n";
  34840. break;
  34841. default:
  34842. if (value) {
  34843. result += "#define " + prop + "\n";
  34844. }
  34845. break;
  34846. }
  34847. }
  34848. return result;
  34849. };
  34850. return MaterialDefines;
  34851. }());
  34852. BABYLON.MaterialDefines = MaterialDefines;
  34853. /**
  34854. * Base class for the main features of a material in Babylon.js
  34855. */
  34856. var Material = /** @class */ (function () {
  34857. /**
  34858. * Creates a material instance
  34859. * @param name defines the name of the material
  34860. * @param scene defines the scene to reference
  34861. * @param doNotAdd specifies if the material should be added to the scene
  34862. */
  34863. function Material(name, scene, doNotAdd) {
  34864. /**
  34865. * Specifies if the ready state should be checked on each call
  34866. */
  34867. this.checkReadyOnEveryCall = false;
  34868. /**
  34869. * Specifies if the ready state should be checked once
  34870. */
  34871. this.checkReadyOnlyOnce = false;
  34872. /**
  34873. * The state of the material
  34874. */
  34875. this.state = "";
  34876. /**
  34877. * The alpha value of the material
  34878. */
  34879. this._alpha = 1.0;
  34880. /**
  34881. * Specifies if back face culling is enabled
  34882. */
  34883. this._backFaceCulling = true;
  34884. /**
  34885. * Specifies if the material should be serialized
  34886. */
  34887. this.doNotSerialize = false;
  34888. /**
  34889. * Specifies if the effect should be stored on sub meshes
  34890. */
  34891. this.storeEffectOnSubMeshes = false;
  34892. /**
  34893. * An event triggered when the material is disposed
  34894. */
  34895. this.onDisposeObservable = new BABYLON.Observable();
  34896. /**
  34897. * Stores the value of the alpha mode
  34898. */
  34899. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34900. /**
  34901. * Stores the state of the need depth pre-pass value
  34902. */
  34903. this._needDepthPrePass = false;
  34904. /**
  34905. * Specifies if depth writing should be disabled
  34906. */
  34907. this.disableDepthWrite = false;
  34908. /**
  34909. * Specifies if depth writing should be forced
  34910. */
  34911. this.forceDepthWrite = false;
  34912. /**
  34913. * Specifies if there should be a separate pass for culling
  34914. */
  34915. this.separateCullingPass = false;
  34916. /**
  34917. * Stores the state specifing if fog should be enabled
  34918. */
  34919. this._fogEnabled = true;
  34920. /**
  34921. * Stores the size of points
  34922. */
  34923. this.pointSize = 1.0;
  34924. /**
  34925. * Stores the z offset value
  34926. */
  34927. this.zOffset = 0;
  34928. /**
  34929. * @hidden
  34930. * Specifies if the material was previously ready
  34931. */
  34932. this._wasPreviouslyReady = false;
  34933. /**
  34934. * Stores the fill mode state
  34935. */
  34936. this._fillMode = Material.TriangleFillMode;
  34937. this.name = name;
  34938. this.id = name || BABYLON.Tools.RandomId();
  34939. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34940. this.uniqueId = this._scene.getUniqueId();
  34941. if (this._scene.useRightHandedSystem) {
  34942. this.sideOrientation = Material.ClockWiseSideOrientation;
  34943. }
  34944. else {
  34945. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34946. }
  34947. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34948. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34949. if (!doNotAdd) {
  34950. this._scene.materials.push(this);
  34951. }
  34952. }
  34953. Object.defineProperty(Material, "TriangleFillMode", {
  34954. /**
  34955. * Returns the triangle fill mode
  34956. */
  34957. get: function () {
  34958. return Material._TriangleFillMode;
  34959. },
  34960. enumerable: true,
  34961. configurable: true
  34962. });
  34963. Object.defineProperty(Material, "WireFrameFillMode", {
  34964. /**
  34965. * Returns the wireframe mode
  34966. */
  34967. get: function () {
  34968. return Material._WireFrameFillMode;
  34969. },
  34970. enumerable: true,
  34971. configurable: true
  34972. });
  34973. Object.defineProperty(Material, "PointFillMode", {
  34974. /**
  34975. * Returns the point fill mode
  34976. */
  34977. get: function () {
  34978. return Material._PointFillMode;
  34979. },
  34980. enumerable: true,
  34981. configurable: true
  34982. });
  34983. Object.defineProperty(Material, "PointListDrawMode", {
  34984. /**
  34985. * Returns the point list draw mode
  34986. */
  34987. get: function () {
  34988. return Material._PointListDrawMode;
  34989. },
  34990. enumerable: true,
  34991. configurable: true
  34992. });
  34993. Object.defineProperty(Material, "LineListDrawMode", {
  34994. /**
  34995. * Returns the line list draw mode
  34996. */
  34997. get: function () {
  34998. return Material._LineListDrawMode;
  34999. },
  35000. enumerable: true,
  35001. configurable: true
  35002. });
  35003. Object.defineProperty(Material, "LineLoopDrawMode", {
  35004. /**
  35005. * Returns the line loop draw mode
  35006. */
  35007. get: function () {
  35008. return Material._LineLoopDrawMode;
  35009. },
  35010. enumerable: true,
  35011. configurable: true
  35012. });
  35013. Object.defineProperty(Material, "LineStripDrawMode", {
  35014. /**
  35015. * Returns the line strip draw mode
  35016. */
  35017. get: function () {
  35018. return Material._LineStripDrawMode;
  35019. },
  35020. enumerable: true,
  35021. configurable: true
  35022. });
  35023. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35024. /**
  35025. * Returns the triangle strip draw mode
  35026. */
  35027. get: function () {
  35028. return Material._TriangleStripDrawMode;
  35029. },
  35030. enumerable: true,
  35031. configurable: true
  35032. });
  35033. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35034. /**
  35035. * Returns the triangle fan draw mode
  35036. */
  35037. get: function () {
  35038. return Material._TriangleFanDrawMode;
  35039. },
  35040. enumerable: true,
  35041. configurable: true
  35042. });
  35043. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35044. /**
  35045. * Returns the clock-wise side orientation
  35046. */
  35047. get: function () {
  35048. return Material._ClockWiseSideOrientation;
  35049. },
  35050. enumerable: true,
  35051. configurable: true
  35052. });
  35053. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35054. /**
  35055. * Returns the counter clock-wise side orientation
  35056. */
  35057. get: function () {
  35058. return Material._CounterClockWiseSideOrientation;
  35059. },
  35060. enumerable: true,
  35061. configurable: true
  35062. });
  35063. Object.defineProperty(Material, "TextureDirtyFlag", {
  35064. /**
  35065. * Returns the dirty texture flag value
  35066. */
  35067. get: function () {
  35068. return Material._TextureDirtyFlag;
  35069. },
  35070. enumerable: true,
  35071. configurable: true
  35072. });
  35073. Object.defineProperty(Material, "LightDirtyFlag", {
  35074. /**
  35075. * Returns the dirty light flag value
  35076. */
  35077. get: function () {
  35078. return Material._LightDirtyFlag;
  35079. },
  35080. enumerable: true,
  35081. configurable: true
  35082. });
  35083. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35084. /**
  35085. * Returns the dirty fresnel flag value
  35086. */
  35087. get: function () {
  35088. return Material._FresnelDirtyFlag;
  35089. },
  35090. enumerable: true,
  35091. configurable: true
  35092. });
  35093. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35094. /**
  35095. * Returns the dirty attributes flag value
  35096. */
  35097. get: function () {
  35098. return Material._AttributesDirtyFlag;
  35099. },
  35100. enumerable: true,
  35101. configurable: true
  35102. });
  35103. Object.defineProperty(Material, "MiscDirtyFlag", {
  35104. /**
  35105. * Returns the dirty misc flag value
  35106. */
  35107. get: function () {
  35108. return Material._MiscDirtyFlag;
  35109. },
  35110. enumerable: true,
  35111. configurable: true
  35112. });
  35113. Object.defineProperty(Material.prototype, "alpha", {
  35114. /**
  35115. * Gets the alpha value of the material
  35116. */
  35117. get: function () {
  35118. return this._alpha;
  35119. },
  35120. /**
  35121. * Sets the alpha value of the material
  35122. */
  35123. set: function (value) {
  35124. if (this._alpha === value) {
  35125. return;
  35126. }
  35127. this._alpha = value;
  35128. this.markAsDirty(Material.MiscDirtyFlag);
  35129. },
  35130. enumerable: true,
  35131. configurable: true
  35132. });
  35133. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35134. /**
  35135. * Gets the back-face culling state
  35136. */
  35137. get: function () {
  35138. return this._backFaceCulling;
  35139. },
  35140. /**
  35141. * Sets the back-face culling state
  35142. */
  35143. set: function (value) {
  35144. if (this._backFaceCulling === value) {
  35145. return;
  35146. }
  35147. this._backFaceCulling = value;
  35148. this.markAsDirty(Material.TextureDirtyFlag);
  35149. },
  35150. enumerable: true,
  35151. configurable: true
  35152. });
  35153. Object.defineProperty(Material.prototype, "onDispose", {
  35154. /**
  35155. * Called during a dispose event
  35156. */
  35157. set: function (callback) {
  35158. if (this._onDisposeObserver) {
  35159. this.onDisposeObservable.remove(this._onDisposeObserver);
  35160. }
  35161. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35162. },
  35163. enumerable: true,
  35164. configurable: true
  35165. });
  35166. Object.defineProperty(Material.prototype, "onBindObservable", {
  35167. /**
  35168. * An event triggered when the material is bound
  35169. */
  35170. get: function () {
  35171. if (!this._onBindObservable) {
  35172. this._onBindObservable = new BABYLON.Observable();
  35173. }
  35174. return this._onBindObservable;
  35175. },
  35176. enumerable: true,
  35177. configurable: true
  35178. });
  35179. Object.defineProperty(Material.prototype, "onBind", {
  35180. /**
  35181. * Called during a bind event
  35182. */
  35183. set: function (callback) {
  35184. if (this._onBindObserver) {
  35185. this.onBindObservable.remove(this._onBindObserver);
  35186. }
  35187. this._onBindObserver = this.onBindObservable.add(callback);
  35188. },
  35189. enumerable: true,
  35190. configurable: true
  35191. });
  35192. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  35193. /**
  35194. * An event triggered when the material is unbound
  35195. */
  35196. get: function () {
  35197. if (!this._onUnBindObservable) {
  35198. this._onUnBindObservable = new BABYLON.Observable();
  35199. }
  35200. return this._onUnBindObservable;
  35201. },
  35202. enumerable: true,
  35203. configurable: true
  35204. });
  35205. Object.defineProperty(Material.prototype, "alphaMode", {
  35206. /**
  35207. * Gets the value of the alpha mode
  35208. */
  35209. get: function () {
  35210. return this._alphaMode;
  35211. },
  35212. /**
  35213. * Sets the value of the alpha mode.
  35214. *
  35215. * | Value | Type | Description |
  35216. * | --- | --- | --- |
  35217. * | 0 | ALPHA_DISABLE | |
  35218. * | 1 | ALPHA_ADD | |
  35219. * | 2 | ALPHA_COMBINE | |
  35220. * | 3 | ALPHA_SUBTRACT | |
  35221. * | 4 | ALPHA_MULTIPLY | |
  35222. * | 5 | ALPHA_MAXIMIZED | |
  35223. * | 6 | ALPHA_ONEONE | |
  35224. * | 7 | ALPHA_PREMULTIPLIED | |
  35225. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35226. * | 9 | ALPHA_INTERPOLATE | |
  35227. * | 10 | ALPHA_SCREENMODE | |
  35228. *
  35229. */
  35230. set: function (value) {
  35231. if (this._alphaMode === value) {
  35232. return;
  35233. }
  35234. this._alphaMode = value;
  35235. this.markAsDirty(Material.TextureDirtyFlag);
  35236. },
  35237. enumerable: true,
  35238. configurable: true
  35239. });
  35240. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35241. /**
  35242. * Gets the depth pre-pass value
  35243. */
  35244. get: function () {
  35245. return this._needDepthPrePass;
  35246. },
  35247. /**
  35248. * Sets the need depth pre-pass value
  35249. */
  35250. set: function (value) {
  35251. if (this._needDepthPrePass === value) {
  35252. return;
  35253. }
  35254. this._needDepthPrePass = value;
  35255. if (this._needDepthPrePass) {
  35256. this.checkReadyOnEveryCall = true;
  35257. }
  35258. },
  35259. enumerable: true,
  35260. configurable: true
  35261. });
  35262. Object.defineProperty(Material.prototype, "fogEnabled", {
  35263. /**
  35264. * Gets the value of the fog enabled state
  35265. */
  35266. get: function () {
  35267. return this._fogEnabled;
  35268. },
  35269. /**
  35270. * Sets the state for enabling fog
  35271. */
  35272. set: function (value) {
  35273. if (this._fogEnabled === value) {
  35274. return;
  35275. }
  35276. this._fogEnabled = value;
  35277. this.markAsDirty(Material.MiscDirtyFlag);
  35278. },
  35279. enumerable: true,
  35280. configurable: true
  35281. });
  35282. Object.defineProperty(Material.prototype, "wireframe", {
  35283. /**
  35284. * Gets a value specifying if wireframe mode is enabled
  35285. */
  35286. get: function () {
  35287. switch (this._fillMode) {
  35288. case Material.WireFrameFillMode:
  35289. case Material.LineListDrawMode:
  35290. case Material.LineLoopDrawMode:
  35291. case Material.LineStripDrawMode:
  35292. return true;
  35293. }
  35294. return this._scene.forceWireframe;
  35295. },
  35296. /**
  35297. * Sets the state of wireframe mode
  35298. */
  35299. set: function (value) {
  35300. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35301. },
  35302. enumerable: true,
  35303. configurable: true
  35304. });
  35305. Object.defineProperty(Material.prototype, "pointsCloud", {
  35306. /**
  35307. * Gets the value specifying if point clouds are enabled
  35308. */
  35309. get: function () {
  35310. switch (this._fillMode) {
  35311. case Material.PointFillMode:
  35312. case Material.PointListDrawMode:
  35313. return true;
  35314. }
  35315. return this._scene.forcePointsCloud;
  35316. },
  35317. /**
  35318. * Sets the state of point cloud mode
  35319. */
  35320. set: function (value) {
  35321. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35322. },
  35323. enumerable: true,
  35324. configurable: true
  35325. });
  35326. Object.defineProperty(Material.prototype, "fillMode", {
  35327. /**
  35328. * Gets the material fill mode
  35329. */
  35330. get: function () {
  35331. return this._fillMode;
  35332. },
  35333. /**
  35334. * Sets the material fill mode
  35335. */
  35336. set: function (value) {
  35337. if (this._fillMode === value) {
  35338. return;
  35339. }
  35340. this._fillMode = value;
  35341. this.markAsDirty(Material.MiscDirtyFlag);
  35342. },
  35343. enumerable: true,
  35344. configurable: true
  35345. });
  35346. /**
  35347. * Returns a string representation of the current material
  35348. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35349. * @returns a string with material information
  35350. */
  35351. Material.prototype.toString = function (fullDetails) {
  35352. var ret = "Name: " + this.name;
  35353. if (fullDetails) {
  35354. }
  35355. return ret;
  35356. };
  35357. /**
  35358. * Gets the class name of the material
  35359. * @returns a string with the class name of the material
  35360. */
  35361. Material.prototype.getClassName = function () {
  35362. return "Material";
  35363. };
  35364. Object.defineProperty(Material.prototype, "isFrozen", {
  35365. /**
  35366. * Specifies if updates for the material been locked
  35367. */
  35368. get: function () {
  35369. return this.checkReadyOnlyOnce;
  35370. },
  35371. enumerable: true,
  35372. configurable: true
  35373. });
  35374. /**
  35375. * Locks updates for the material
  35376. */
  35377. Material.prototype.freeze = function () {
  35378. this.checkReadyOnlyOnce = true;
  35379. };
  35380. /**
  35381. * Unlocks updates for the material
  35382. */
  35383. Material.prototype.unfreeze = function () {
  35384. this.checkReadyOnlyOnce = false;
  35385. };
  35386. /**
  35387. * Specifies if the material is ready to be used
  35388. * @param mesh defines the mesh to check
  35389. * @param useInstances specifies if instances should be used
  35390. * @returns a boolean indicating if the material is ready to be used
  35391. */
  35392. Material.prototype.isReady = function (mesh, useInstances) {
  35393. return true;
  35394. };
  35395. /**
  35396. * Specifies that the submesh is ready to be used
  35397. * @param mesh defines the mesh to check
  35398. * @param subMesh defines which submesh to check
  35399. * @param useInstances specifies that instances should be used
  35400. * @returns a boolean indicating that the submesh is ready or not
  35401. */
  35402. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35403. return false;
  35404. };
  35405. /**
  35406. * Returns the material effect
  35407. * @returns the effect associated with the material
  35408. */
  35409. Material.prototype.getEffect = function () {
  35410. return this._effect;
  35411. };
  35412. /**
  35413. * Returns the current scene
  35414. * @returns a Scene
  35415. */
  35416. Material.prototype.getScene = function () {
  35417. return this._scene;
  35418. };
  35419. /**
  35420. * Specifies if the material will require alpha blending
  35421. * @returns a boolean specifying if alpha blending is needed
  35422. */
  35423. Material.prototype.needAlphaBlending = function () {
  35424. return (this.alpha < 1.0);
  35425. };
  35426. /**
  35427. * Specifies if the mesh will require alpha blending
  35428. * @param mesh defines the mesh to check
  35429. * @returns a boolean specifying if alpha blending is needed for the mesh
  35430. */
  35431. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35432. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35433. };
  35434. /**
  35435. * Specifies if this material should be rendered in alpha test mode
  35436. * @returns a boolean specifying if an alpha test is needed.
  35437. */
  35438. Material.prototype.needAlphaTesting = function () {
  35439. return false;
  35440. };
  35441. /**
  35442. * Gets the texture used for the alpha test
  35443. * @returns the texture to use for alpha testing
  35444. */
  35445. Material.prototype.getAlphaTestTexture = function () {
  35446. return null;
  35447. };
  35448. /**
  35449. * Marks the material to indicate that it needs to be re-calculated
  35450. */
  35451. Material.prototype.markDirty = function () {
  35452. this._wasPreviouslyReady = false;
  35453. };
  35454. /** @hidden */
  35455. Material.prototype._preBind = function (effect, overrideOrientation) {
  35456. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35457. var engine = this._scene.getEngine();
  35458. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35459. var reverse = orientation === Material.ClockWiseSideOrientation;
  35460. engine.enableEffect(effect ? effect : this._effect);
  35461. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35462. return reverse;
  35463. };
  35464. /**
  35465. * Binds the material to the mesh
  35466. * @param world defines the world transformation matrix
  35467. * @param mesh defines the mesh to bind the material to
  35468. */
  35469. Material.prototype.bind = function (world, mesh) {
  35470. };
  35471. /**
  35472. * Binds the submesh to the material
  35473. * @param world defines the world transformation matrix
  35474. * @param mesh defines the mesh containing the submesh
  35475. * @param subMesh defines the submesh to bind the material to
  35476. */
  35477. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35478. };
  35479. /**
  35480. * Binds the world matrix to the material
  35481. * @param world defines the world transformation matrix
  35482. */
  35483. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35484. };
  35485. /**
  35486. * Binds the scene's uniform buffer to the effect.
  35487. * @param effect defines the effect to bind to the scene uniform buffer
  35488. * @param sceneUbo defines the uniform buffer storing scene data
  35489. */
  35490. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35491. sceneUbo.bindToEffect(effect, "Scene");
  35492. };
  35493. /**
  35494. * Binds the view matrix to the effect
  35495. * @param effect defines the effect to bind the view matrix to
  35496. */
  35497. Material.prototype.bindView = function (effect) {
  35498. if (!this._useUBO) {
  35499. effect.setMatrix("view", this.getScene().getViewMatrix());
  35500. }
  35501. else {
  35502. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35503. }
  35504. };
  35505. /**
  35506. * Binds the view projection matrix to the effect
  35507. * @param effect defines the effect to bind the view projection matrix to
  35508. */
  35509. Material.prototype.bindViewProjection = function (effect) {
  35510. if (!this._useUBO) {
  35511. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35512. }
  35513. else {
  35514. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35515. }
  35516. };
  35517. /**
  35518. * Specifies if material alpha testing should be turned on for the mesh
  35519. * @param mesh defines the mesh to check
  35520. */
  35521. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35522. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35523. };
  35524. /**
  35525. * Processes to execute after binding the material to a mesh
  35526. * @param mesh defines the rendered mesh
  35527. */
  35528. Material.prototype._afterBind = function (mesh) {
  35529. this._scene._cachedMaterial = this;
  35530. if (mesh) {
  35531. this._scene._cachedVisibility = mesh.visibility;
  35532. }
  35533. else {
  35534. this._scene._cachedVisibility = 1;
  35535. }
  35536. if (this._onBindObservable && mesh) {
  35537. this._onBindObservable.notifyObservers(mesh);
  35538. }
  35539. if (this.disableDepthWrite) {
  35540. var engine = this._scene.getEngine();
  35541. this._cachedDepthWriteState = engine.getDepthWrite();
  35542. engine.setDepthWrite(false);
  35543. }
  35544. };
  35545. /**
  35546. * Unbinds the material from the mesh
  35547. */
  35548. Material.prototype.unbind = function () {
  35549. if (this._onUnBindObservable) {
  35550. this._onUnBindObservable.notifyObservers(this);
  35551. }
  35552. if (this.disableDepthWrite) {
  35553. var engine = this._scene.getEngine();
  35554. engine.setDepthWrite(this._cachedDepthWriteState);
  35555. }
  35556. };
  35557. /**
  35558. * Gets the active textures from the material
  35559. * @returns an array of textures
  35560. */
  35561. Material.prototype.getActiveTextures = function () {
  35562. return [];
  35563. };
  35564. /**
  35565. * Specifies if the material uses a texture
  35566. * @param texture defines the texture to check against the material
  35567. * @returns a boolean specifying if the material uses the texture
  35568. */
  35569. Material.prototype.hasTexture = function (texture) {
  35570. return false;
  35571. };
  35572. /**
  35573. * Makes a duplicate of the material, and gives it a new name
  35574. * @param name defines the new name for the duplicated material
  35575. * @returns the cloned material
  35576. */
  35577. Material.prototype.clone = function (name) {
  35578. return null;
  35579. };
  35580. /**
  35581. * Gets the meshes bound to the material
  35582. * @returns an array of meshes bound to the material
  35583. */
  35584. Material.prototype.getBindedMeshes = function () {
  35585. var result = new Array();
  35586. for (var index = 0; index < this._scene.meshes.length; index++) {
  35587. var mesh = this._scene.meshes[index];
  35588. if (mesh.material === this) {
  35589. result.push(mesh);
  35590. }
  35591. }
  35592. return result;
  35593. };
  35594. /**
  35595. * Force shader compilation
  35596. * @param mesh defines the mesh associated with this material
  35597. * @param onCompiled defines a function to execute once the material is compiled
  35598. * @param options defines the options to configure the compilation
  35599. */
  35600. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35601. var _this = this;
  35602. var localOptions = __assign({ clipPlane: false }, options);
  35603. var subMesh = new BABYLON.BaseSubMesh();
  35604. var scene = this.getScene();
  35605. var checkReady = function () {
  35606. if (!_this._scene || !_this._scene.getEngine()) {
  35607. return;
  35608. }
  35609. if (subMesh._materialDefines) {
  35610. subMesh._materialDefines._renderId = -1;
  35611. }
  35612. var clipPlaneState = scene.clipPlane;
  35613. if (localOptions.clipPlane) {
  35614. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35615. }
  35616. if (_this.storeEffectOnSubMeshes) {
  35617. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35618. if (onCompiled) {
  35619. onCompiled(_this);
  35620. }
  35621. }
  35622. else {
  35623. setTimeout(checkReady, 16);
  35624. }
  35625. }
  35626. else {
  35627. if (_this.isReady(mesh)) {
  35628. if (onCompiled) {
  35629. onCompiled(_this);
  35630. }
  35631. }
  35632. else {
  35633. setTimeout(checkReady, 16);
  35634. }
  35635. }
  35636. if (localOptions.clipPlane) {
  35637. scene.clipPlane = clipPlaneState;
  35638. }
  35639. };
  35640. checkReady();
  35641. };
  35642. /**
  35643. * Force shader compilation
  35644. * @param mesh defines the mesh that will use this material
  35645. * @param options defines additional options for compiling the shaders
  35646. * @returns a promise that resolves when the compilation completes
  35647. */
  35648. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35649. var _this = this;
  35650. return new Promise(function (resolve) {
  35651. _this.forceCompilation(mesh, function () {
  35652. resolve();
  35653. }, options);
  35654. });
  35655. };
  35656. /**
  35657. * Marks a define in the material to indicate that it needs to be re-computed
  35658. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35659. */
  35660. Material.prototype.markAsDirty = function (flag) {
  35661. if (flag & Material.TextureDirtyFlag) {
  35662. this._markAllSubMeshesAsTexturesDirty();
  35663. }
  35664. if (flag & Material.LightDirtyFlag) {
  35665. this._markAllSubMeshesAsLightsDirty();
  35666. }
  35667. if (flag & Material.FresnelDirtyFlag) {
  35668. this._markAllSubMeshesAsFresnelDirty();
  35669. }
  35670. if (flag & Material.AttributesDirtyFlag) {
  35671. this._markAllSubMeshesAsAttributesDirty();
  35672. }
  35673. if (flag & Material.MiscDirtyFlag) {
  35674. this._markAllSubMeshesAsMiscDirty();
  35675. }
  35676. this.getScene().resetCachedMaterial();
  35677. };
  35678. /**
  35679. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35680. * @param func defines a function which checks material defines against the submeshes
  35681. */
  35682. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35683. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35684. var mesh = _a[_i];
  35685. if (!mesh.subMeshes) {
  35686. continue;
  35687. }
  35688. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35689. var subMesh = _c[_b];
  35690. if (subMesh.getMaterial() !== this) {
  35691. continue;
  35692. }
  35693. if (!subMesh._materialDefines) {
  35694. continue;
  35695. }
  35696. func(subMesh._materialDefines);
  35697. }
  35698. }
  35699. };
  35700. /**
  35701. * Indicates that image processing needs to be re-calculated for all submeshes
  35702. */
  35703. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35704. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35705. };
  35706. /**
  35707. * Indicates that textures need to be re-calculated for all submeshes
  35708. */
  35709. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35710. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35711. };
  35712. /**
  35713. * Indicates that fresnel needs to be re-calculated for all submeshes
  35714. */
  35715. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35716. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35717. };
  35718. /**
  35719. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35720. */
  35721. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35722. this._markAllSubMeshesAsDirty(function (defines) {
  35723. defines.markAsFresnelDirty();
  35724. defines.markAsMiscDirty();
  35725. });
  35726. };
  35727. /**
  35728. * Indicates that lights need to be re-calculated for all submeshes
  35729. */
  35730. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35731. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35732. };
  35733. /**
  35734. * Indicates that attributes need to be re-calculated for all submeshes
  35735. */
  35736. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35737. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35738. };
  35739. /**
  35740. * Indicates that misc needs to be re-calculated for all submeshes
  35741. */
  35742. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35743. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35744. };
  35745. /**
  35746. * Indicates that textures and misc need to be re-calculated for all submeshes
  35747. */
  35748. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35749. this._markAllSubMeshesAsDirty(function (defines) {
  35750. defines.markAsTexturesDirty();
  35751. defines.markAsMiscDirty();
  35752. });
  35753. };
  35754. /**
  35755. * Disposes the material
  35756. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35757. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35758. */
  35759. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35760. // Animations
  35761. this.getScene().stopAnimation(this);
  35762. this.getScene().freeProcessedMaterials();
  35763. // Remove from scene
  35764. var index = this._scene.materials.indexOf(this);
  35765. if (index >= 0) {
  35766. this._scene.materials.splice(index, 1);
  35767. }
  35768. // Remove from meshes
  35769. for (index = 0; index < this._scene.meshes.length; index++) {
  35770. var mesh = this._scene.meshes[index];
  35771. if (mesh.material === this) {
  35772. mesh.material = null;
  35773. if (mesh.geometry) {
  35774. var geometry = (mesh.geometry);
  35775. if (this.storeEffectOnSubMeshes) {
  35776. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35777. var subMesh = _a[_i];
  35778. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35779. if (forceDisposeEffect && subMesh._materialEffect) {
  35780. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35781. }
  35782. }
  35783. }
  35784. else {
  35785. geometry._releaseVertexArrayObject(this._effect);
  35786. }
  35787. }
  35788. }
  35789. }
  35790. this._uniformBuffer.dispose();
  35791. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35792. if (forceDisposeEffect && this._effect) {
  35793. if (!this.storeEffectOnSubMeshes) {
  35794. this._scene.getEngine()._releaseEffect(this._effect);
  35795. }
  35796. this._effect = null;
  35797. }
  35798. // Callback
  35799. this.onDisposeObservable.notifyObservers(this);
  35800. this.onDisposeObservable.clear();
  35801. if (this._onBindObservable) {
  35802. this._onBindObservable.clear();
  35803. }
  35804. if (this._onUnBindObservable) {
  35805. this._onUnBindObservable.clear();
  35806. }
  35807. };
  35808. /**
  35809. * Serializes this material
  35810. * @returns the serialized material object
  35811. */
  35812. Material.prototype.serialize = function () {
  35813. return BABYLON.SerializationHelper.Serialize(this);
  35814. };
  35815. /**
  35816. * Creates a MultiMaterial from parsed MultiMaterial data.
  35817. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35818. * @param scene defines the hosting scene
  35819. * @returns a new MultiMaterial
  35820. */
  35821. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35822. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35823. multiMaterial.id = parsedMultiMaterial.id;
  35824. if (BABYLON.Tags) {
  35825. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35826. }
  35827. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35828. var subMatId = parsedMultiMaterial.materials[matIndex];
  35829. if (subMatId) {
  35830. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35831. }
  35832. else {
  35833. multiMaterial.subMaterials.push(null);
  35834. }
  35835. }
  35836. return multiMaterial;
  35837. };
  35838. /**
  35839. * Creates a material from parsed material data
  35840. * @param parsedMaterial defines parsed material data
  35841. * @param scene defines the hosting scene
  35842. * @param rootUrl defines the root URL to use to load textures
  35843. * @returns a new material
  35844. */
  35845. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35846. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35847. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35848. }
  35849. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35850. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35851. if (!BABYLON.LegacyPBRMaterial) {
  35852. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35853. return;
  35854. }
  35855. }
  35856. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35857. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35858. };
  35859. // Triangle views
  35860. Material._TriangleFillMode = 0;
  35861. Material._WireFrameFillMode = 1;
  35862. Material._PointFillMode = 2;
  35863. // Draw modes
  35864. Material._PointListDrawMode = 3;
  35865. Material._LineListDrawMode = 4;
  35866. Material._LineLoopDrawMode = 5;
  35867. Material._LineStripDrawMode = 6;
  35868. Material._TriangleStripDrawMode = 7;
  35869. Material._TriangleFanDrawMode = 8;
  35870. /**
  35871. * Stores the clock-wise side orientation
  35872. */
  35873. Material._ClockWiseSideOrientation = 0;
  35874. /**
  35875. * Stores the counter clock-wise side orientation
  35876. */
  35877. Material._CounterClockWiseSideOrientation = 1;
  35878. /**
  35879. * The dirty texture flag value
  35880. */
  35881. Material._TextureDirtyFlag = 1;
  35882. /**
  35883. * The dirty light flag value
  35884. */
  35885. Material._LightDirtyFlag = 2;
  35886. /**
  35887. * The dirty fresnel flag value
  35888. */
  35889. Material._FresnelDirtyFlag = 4;
  35890. /**
  35891. * The dirty attribute flag value
  35892. */
  35893. Material._AttributesDirtyFlag = 8;
  35894. /**
  35895. * The dirty misc flag value
  35896. */
  35897. Material._MiscDirtyFlag = 16;
  35898. __decorate([
  35899. BABYLON.serialize()
  35900. ], Material.prototype, "id", void 0);
  35901. __decorate([
  35902. BABYLON.serialize()
  35903. ], Material.prototype, "uniqueId", void 0);
  35904. __decorate([
  35905. BABYLON.serialize()
  35906. ], Material.prototype, "name", void 0);
  35907. __decorate([
  35908. BABYLON.serialize()
  35909. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35910. __decorate([
  35911. BABYLON.serialize()
  35912. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35913. __decorate([
  35914. BABYLON.serialize()
  35915. ], Material.prototype, "state", void 0);
  35916. __decorate([
  35917. BABYLON.serialize("alpha")
  35918. ], Material.prototype, "_alpha", void 0);
  35919. __decorate([
  35920. BABYLON.serialize("backFaceCulling")
  35921. ], Material.prototype, "_backFaceCulling", void 0);
  35922. __decorate([
  35923. BABYLON.serialize()
  35924. ], Material.prototype, "sideOrientation", void 0);
  35925. __decorate([
  35926. BABYLON.serialize("alphaMode")
  35927. ], Material.prototype, "_alphaMode", void 0);
  35928. __decorate([
  35929. BABYLON.serialize()
  35930. ], Material.prototype, "_needDepthPrePass", void 0);
  35931. __decorate([
  35932. BABYLON.serialize()
  35933. ], Material.prototype, "disableDepthWrite", void 0);
  35934. __decorate([
  35935. BABYLON.serialize()
  35936. ], Material.prototype, "forceDepthWrite", void 0);
  35937. __decorate([
  35938. BABYLON.serialize()
  35939. ], Material.prototype, "separateCullingPass", void 0);
  35940. __decorate([
  35941. BABYLON.serialize("fogEnabled")
  35942. ], Material.prototype, "_fogEnabled", void 0);
  35943. __decorate([
  35944. BABYLON.serialize()
  35945. ], Material.prototype, "pointSize", void 0);
  35946. __decorate([
  35947. BABYLON.serialize()
  35948. ], Material.prototype, "zOffset", void 0);
  35949. __decorate([
  35950. BABYLON.serialize()
  35951. ], Material.prototype, "wireframe", null);
  35952. __decorate([
  35953. BABYLON.serialize()
  35954. ], Material.prototype, "pointsCloud", null);
  35955. __decorate([
  35956. BABYLON.serialize()
  35957. ], Material.prototype, "fillMode", null);
  35958. return Material;
  35959. }());
  35960. BABYLON.Material = Material;
  35961. })(BABYLON || (BABYLON = {}));
  35962. //# sourceMappingURL=babylon.material.js.map
  35963. var BABYLON;
  35964. (function (BABYLON) {
  35965. var UniformBuffer = /** @class */ (function () {
  35966. /**
  35967. * Uniform buffer objects.
  35968. *
  35969. * Handles blocks of uniform on the GPU.
  35970. *
  35971. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35972. *
  35973. * For more information, please refer to :
  35974. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35975. */
  35976. function UniformBuffer(engine, data, dynamic) {
  35977. this._engine = engine;
  35978. this._noUBO = !engine.supportsUniformBuffers;
  35979. this._dynamic = dynamic;
  35980. this._data = data || [];
  35981. this._uniformLocations = {};
  35982. this._uniformSizes = {};
  35983. this._uniformLocationPointer = 0;
  35984. this._needSync = false;
  35985. if (this._noUBO) {
  35986. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35987. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35988. this.updateFloat = this._updateFloatForEffect;
  35989. this.updateFloat2 = this._updateFloat2ForEffect;
  35990. this.updateFloat3 = this._updateFloat3ForEffect;
  35991. this.updateFloat4 = this._updateFloat4ForEffect;
  35992. this.updateMatrix = this._updateMatrixForEffect;
  35993. this.updateVector3 = this._updateVector3ForEffect;
  35994. this.updateVector4 = this._updateVector4ForEffect;
  35995. this.updateColor3 = this._updateColor3ForEffect;
  35996. this.updateColor4 = this._updateColor4ForEffect;
  35997. }
  35998. else {
  35999. this._engine._uniformBuffers.push(this);
  36000. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36001. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36002. this.updateFloat = this._updateFloatForUniform;
  36003. this.updateFloat2 = this._updateFloat2ForUniform;
  36004. this.updateFloat3 = this._updateFloat3ForUniform;
  36005. this.updateFloat4 = this._updateFloat4ForUniform;
  36006. this.updateMatrix = this._updateMatrixForUniform;
  36007. this.updateVector3 = this._updateVector3ForUniform;
  36008. this.updateVector4 = this._updateVector4ForUniform;
  36009. this.updateColor3 = this._updateColor3ForUniform;
  36010. this.updateColor4 = this._updateColor4ForUniform;
  36011. }
  36012. }
  36013. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36014. // Properties
  36015. /**
  36016. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36017. * or just falling back on setUniformXXX calls.
  36018. */
  36019. get: function () {
  36020. return !this._noUBO;
  36021. },
  36022. enumerable: true,
  36023. configurable: true
  36024. });
  36025. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36026. /**
  36027. * Indicates if the WebGL underlying uniform buffer is in sync
  36028. * with the javascript cache data.
  36029. */
  36030. get: function () {
  36031. return !this._needSync;
  36032. },
  36033. enumerable: true,
  36034. configurable: true
  36035. });
  36036. /**
  36037. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36038. * Also, a dynamic UniformBuffer will disable cache verification and always
  36039. * update the underlying WebGL uniform buffer to the GPU.
  36040. */
  36041. UniformBuffer.prototype.isDynamic = function () {
  36042. return this._dynamic !== undefined;
  36043. };
  36044. /**
  36045. * The data cache on JS side.
  36046. */
  36047. UniformBuffer.prototype.getData = function () {
  36048. return this._bufferData;
  36049. };
  36050. /**
  36051. * The underlying WebGL Uniform buffer.
  36052. */
  36053. UniformBuffer.prototype.getBuffer = function () {
  36054. return this._buffer;
  36055. };
  36056. /**
  36057. * std140 layout specifies how to align data within an UBO structure.
  36058. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36059. * for specs.
  36060. */
  36061. UniformBuffer.prototype._fillAlignment = function (size) {
  36062. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36063. // and 4x4 matrices
  36064. // TODO : change if other types are used
  36065. var alignment;
  36066. if (size <= 2) {
  36067. alignment = size;
  36068. }
  36069. else {
  36070. alignment = 4;
  36071. }
  36072. if ((this._uniformLocationPointer % alignment) !== 0) {
  36073. var oldPointer = this._uniformLocationPointer;
  36074. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36075. var diff = this._uniformLocationPointer - oldPointer;
  36076. for (var i = 0; i < diff; i++) {
  36077. this._data.push(0);
  36078. }
  36079. }
  36080. };
  36081. /**
  36082. * Adds an uniform in the buffer.
  36083. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36084. * for the layout to be correct !
  36085. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36086. * @param {number|number[]} size Data size, or data directly.
  36087. */
  36088. UniformBuffer.prototype.addUniform = function (name, size) {
  36089. if (this._noUBO) {
  36090. return;
  36091. }
  36092. if (this._uniformLocations[name] !== undefined) {
  36093. // Already existing uniform
  36094. return;
  36095. }
  36096. // This function must be called in the order of the shader layout !
  36097. // size can be the size of the uniform, or data directly
  36098. var data;
  36099. if (size instanceof Array) {
  36100. data = size;
  36101. size = data.length;
  36102. }
  36103. else {
  36104. size = size;
  36105. data = [];
  36106. // Fill with zeros
  36107. for (var i = 0; i < size; i++) {
  36108. data.push(0);
  36109. }
  36110. }
  36111. this._fillAlignment(size);
  36112. this._uniformSizes[name] = size;
  36113. this._uniformLocations[name] = this._uniformLocationPointer;
  36114. this._uniformLocationPointer += size;
  36115. for (var i = 0; i < size; i++) {
  36116. this._data.push(data[i]);
  36117. }
  36118. this._needSync = true;
  36119. };
  36120. /**
  36121. * Wrapper for addUniform.
  36122. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36123. * @param {Matrix} mat A 4x4 matrix.
  36124. */
  36125. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36126. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36127. };
  36128. /**
  36129. * Wrapper for addUniform.
  36130. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36131. * @param {number} x
  36132. * @param {number} y
  36133. */
  36134. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36135. var temp = [x, y];
  36136. this.addUniform(name, temp);
  36137. };
  36138. /**
  36139. * Wrapper for addUniform.
  36140. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36141. * @param {number} x
  36142. * @param {number} y
  36143. * @param {number} z
  36144. */
  36145. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36146. var temp = [x, y, z];
  36147. this.addUniform(name, temp);
  36148. };
  36149. /**
  36150. * Wrapper for addUniform.
  36151. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36152. * @param {Color3} color
  36153. */
  36154. UniformBuffer.prototype.addColor3 = function (name, color) {
  36155. var temp = new Array();
  36156. color.toArray(temp);
  36157. this.addUniform(name, temp);
  36158. };
  36159. /**
  36160. * Wrapper for addUniform.
  36161. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36162. * @param {Color3} color
  36163. * @param {number} alpha
  36164. */
  36165. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36166. var temp = new Array();
  36167. color.toArray(temp);
  36168. temp.push(alpha);
  36169. this.addUniform(name, temp);
  36170. };
  36171. /**
  36172. * Wrapper for addUniform.
  36173. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36174. * @param {Vector3} vector
  36175. */
  36176. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36177. var temp = new Array();
  36178. vector.toArray(temp);
  36179. this.addUniform(name, temp);
  36180. };
  36181. /**
  36182. * Wrapper for addUniform.
  36183. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36184. */
  36185. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36186. this.addUniform(name, 12);
  36187. };
  36188. /**
  36189. * Wrapper for addUniform.
  36190. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36191. */
  36192. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36193. this.addUniform(name, 8);
  36194. };
  36195. /**
  36196. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36197. */
  36198. UniformBuffer.prototype.create = function () {
  36199. if (this._noUBO) {
  36200. return;
  36201. }
  36202. if (this._buffer) {
  36203. return; // nothing to do
  36204. }
  36205. // See spec, alignment must be filled as a vec4
  36206. this._fillAlignment(4);
  36207. this._bufferData = new Float32Array(this._data);
  36208. this._rebuild();
  36209. this._needSync = true;
  36210. };
  36211. /** @hidden */
  36212. UniformBuffer.prototype._rebuild = function () {
  36213. if (this._noUBO) {
  36214. return;
  36215. }
  36216. if (this._dynamic) {
  36217. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36218. }
  36219. else {
  36220. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36221. }
  36222. };
  36223. /**
  36224. * Updates the WebGL Uniform Buffer on the GPU.
  36225. * If the `dynamic` flag is set to true, no cache comparison is done.
  36226. * Otherwise, the buffer will be updated only if the cache differs.
  36227. */
  36228. UniformBuffer.prototype.update = function () {
  36229. if (!this._buffer) {
  36230. this.create();
  36231. return;
  36232. }
  36233. if (!this._dynamic && !this._needSync) {
  36234. return;
  36235. }
  36236. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36237. this._needSync = false;
  36238. };
  36239. /**
  36240. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36241. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36242. * @param {number[]|Float32Array} data Flattened data
  36243. * @param {number} size Size of the data.
  36244. */
  36245. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36246. var location = this._uniformLocations[uniformName];
  36247. if (location === undefined) {
  36248. if (this._buffer) {
  36249. // Cannot add an uniform if the buffer is already created
  36250. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36251. return;
  36252. }
  36253. this.addUniform(uniformName, size);
  36254. location = this._uniformLocations[uniformName];
  36255. }
  36256. if (!this._buffer) {
  36257. this.create();
  36258. }
  36259. if (!this._dynamic) {
  36260. // Cache for static uniform buffers
  36261. var changed = false;
  36262. for (var i = 0; i < size; i++) {
  36263. if (this._bufferData[location + i] !== data[i]) {
  36264. changed = true;
  36265. this._bufferData[location + i] = data[i];
  36266. }
  36267. }
  36268. this._needSync = this._needSync || changed;
  36269. }
  36270. else {
  36271. // No cache for dynamic
  36272. for (var i = 0; i < size; i++) {
  36273. this._bufferData[location + i] = data[i];
  36274. }
  36275. }
  36276. };
  36277. // Update methods
  36278. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36279. // To match std140, matrix must be realigned
  36280. for (var i = 0; i < 3; i++) {
  36281. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36282. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36283. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36284. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36285. }
  36286. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36287. };
  36288. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36289. this._currentEffect.setMatrix3x3(name, matrix);
  36290. };
  36291. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36292. this._currentEffect.setMatrix2x2(name, matrix);
  36293. };
  36294. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36295. // To match std140, matrix must be realigned
  36296. for (var i = 0; i < 2; i++) {
  36297. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36298. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36299. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36300. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36301. }
  36302. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36303. };
  36304. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36305. this._currentEffect.setFloat(name, x);
  36306. };
  36307. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36308. UniformBuffer._tempBuffer[0] = x;
  36309. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36310. };
  36311. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36312. if (suffix === void 0) { suffix = ""; }
  36313. this._currentEffect.setFloat2(name + suffix, x, y);
  36314. };
  36315. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36316. if (suffix === void 0) { suffix = ""; }
  36317. UniformBuffer._tempBuffer[0] = x;
  36318. UniformBuffer._tempBuffer[1] = y;
  36319. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36320. };
  36321. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36322. if (suffix === void 0) { suffix = ""; }
  36323. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36324. };
  36325. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36326. if (suffix === void 0) { suffix = ""; }
  36327. UniformBuffer._tempBuffer[0] = x;
  36328. UniformBuffer._tempBuffer[1] = y;
  36329. UniformBuffer._tempBuffer[2] = z;
  36330. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36331. };
  36332. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36333. if (suffix === void 0) { suffix = ""; }
  36334. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36335. };
  36336. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36337. if (suffix === void 0) { suffix = ""; }
  36338. UniformBuffer._tempBuffer[0] = x;
  36339. UniformBuffer._tempBuffer[1] = y;
  36340. UniformBuffer._tempBuffer[2] = z;
  36341. UniformBuffer._tempBuffer[3] = w;
  36342. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36343. };
  36344. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36345. this._currentEffect.setMatrix(name, mat);
  36346. };
  36347. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36348. this.updateUniform(name, mat.toArray(), 16);
  36349. };
  36350. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36351. this._currentEffect.setVector3(name, vector);
  36352. };
  36353. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36354. vector.toArray(UniformBuffer._tempBuffer);
  36355. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36356. };
  36357. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36358. this._currentEffect.setVector4(name, vector);
  36359. };
  36360. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36361. vector.toArray(UniformBuffer._tempBuffer);
  36362. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36363. };
  36364. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36365. if (suffix === void 0) { suffix = ""; }
  36366. this._currentEffect.setColor3(name + suffix, color);
  36367. };
  36368. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36369. if (suffix === void 0) { suffix = ""; }
  36370. color.toArray(UniformBuffer._tempBuffer);
  36371. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36372. };
  36373. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36374. if (suffix === void 0) { suffix = ""; }
  36375. this._currentEffect.setColor4(name + suffix, color, alpha);
  36376. };
  36377. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36378. if (suffix === void 0) { suffix = ""; }
  36379. color.toArray(UniformBuffer._tempBuffer);
  36380. UniformBuffer._tempBuffer[3] = alpha;
  36381. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36382. };
  36383. /**
  36384. * Sets a sampler uniform on the effect.
  36385. * @param {string} name Name of the sampler.
  36386. * @param {Texture} texture
  36387. */
  36388. UniformBuffer.prototype.setTexture = function (name, texture) {
  36389. this._currentEffect.setTexture(name, texture);
  36390. };
  36391. /**
  36392. * Directly updates the value of the uniform in the cache AND on the GPU.
  36393. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36394. * @param {number[]|Float32Array} data Flattened data
  36395. */
  36396. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36397. this.updateUniform(uniformName, data, data.length);
  36398. this.update();
  36399. };
  36400. /**
  36401. * Binds this uniform buffer to an effect.
  36402. * @param {Effect} effect
  36403. * @param {string} name Name of the uniform block in the shader.
  36404. */
  36405. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36406. this._currentEffect = effect;
  36407. if (this._noUBO || !this._buffer) {
  36408. return;
  36409. }
  36410. effect.bindUniformBuffer(this._buffer, name);
  36411. };
  36412. /**
  36413. * Disposes the uniform buffer.
  36414. */
  36415. UniformBuffer.prototype.dispose = function () {
  36416. if (this._noUBO) {
  36417. return;
  36418. }
  36419. var index = this._engine._uniformBuffers.indexOf(this);
  36420. if (index !== -1) {
  36421. this._engine._uniformBuffers.splice(index, 1);
  36422. }
  36423. if (!this._buffer) {
  36424. return;
  36425. }
  36426. if (this._engine._releaseBuffer(this._buffer)) {
  36427. this._buffer = null;
  36428. }
  36429. };
  36430. // Pool for avoiding memory leaks
  36431. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36432. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36433. return UniformBuffer;
  36434. }());
  36435. BABYLON.UniformBuffer = UniformBuffer;
  36436. })(BABYLON || (BABYLON = {}));
  36437. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36438. var BABYLON;
  36439. (function (BABYLON) {
  36440. /**
  36441. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36442. */
  36443. var VertexData = /** @class */ (function () {
  36444. function VertexData() {
  36445. }
  36446. /**
  36447. * Uses the passed data array to set the set the values for the specified kind of data
  36448. * @param data a linear array of floating numbers
  36449. * @param kind the type of data that is being set, eg positions, colors etc
  36450. */
  36451. VertexData.prototype.set = function (data, kind) {
  36452. switch (kind) {
  36453. case BABYLON.VertexBuffer.PositionKind:
  36454. this.positions = data;
  36455. break;
  36456. case BABYLON.VertexBuffer.NormalKind:
  36457. this.normals = data;
  36458. break;
  36459. case BABYLON.VertexBuffer.TangentKind:
  36460. this.tangents = data;
  36461. break;
  36462. case BABYLON.VertexBuffer.UVKind:
  36463. this.uvs = data;
  36464. break;
  36465. case BABYLON.VertexBuffer.UV2Kind:
  36466. this.uvs2 = data;
  36467. break;
  36468. case BABYLON.VertexBuffer.UV3Kind:
  36469. this.uvs3 = data;
  36470. break;
  36471. case BABYLON.VertexBuffer.UV4Kind:
  36472. this.uvs4 = data;
  36473. break;
  36474. case BABYLON.VertexBuffer.UV5Kind:
  36475. this.uvs5 = data;
  36476. break;
  36477. case BABYLON.VertexBuffer.UV6Kind:
  36478. this.uvs6 = data;
  36479. break;
  36480. case BABYLON.VertexBuffer.ColorKind:
  36481. this.colors = data;
  36482. break;
  36483. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36484. this.matricesIndices = data;
  36485. break;
  36486. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36487. this.matricesWeights = data;
  36488. break;
  36489. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36490. this.matricesIndicesExtra = data;
  36491. break;
  36492. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36493. this.matricesWeightsExtra = data;
  36494. break;
  36495. }
  36496. };
  36497. /**
  36498. * Associates the vertexData to the passed Mesh.
  36499. * Sets it as updatable or not (default `false`)
  36500. * @param mesh the mesh the vertexData is applied to
  36501. * @param updatable when used and having the value true allows new data to update the vertexData
  36502. * @returns the VertexData
  36503. */
  36504. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36505. this._applyTo(mesh, updatable);
  36506. return this;
  36507. };
  36508. /**
  36509. * Associates the vertexData to the passed Geometry.
  36510. * Sets it as updatable or not (default `false`)
  36511. * @param geometry the geometry the vertexData is applied to
  36512. * @param updatable when used and having the value true allows new data to update the vertexData
  36513. * @returns VertexData
  36514. */
  36515. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36516. this._applyTo(geometry, updatable);
  36517. return this;
  36518. };
  36519. /**
  36520. * Updates the associated mesh
  36521. * @param mesh the mesh to be updated
  36522. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36523. * @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
  36524. * @returns VertexData
  36525. */
  36526. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36527. this._update(mesh);
  36528. return this;
  36529. };
  36530. /**
  36531. * Updates the associated geometry
  36532. * @param geometry the geometry to be updated
  36533. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36534. * @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
  36535. * @returns VertexData.
  36536. */
  36537. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36538. this._update(geometry);
  36539. return this;
  36540. };
  36541. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36542. if (updatable === void 0) { updatable = false; }
  36543. if (this.positions) {
  36544. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36545. }
  36546. if (this.normals) {
  36547. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36548. }
  36549. if (this.tangents) {
  36550. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36551. }
  36552. if (this.uvs) {
  36553. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36554. }
  36555. if (this.uvs2) {
  36556. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36557. }
  36558. if (this.uvs3) {
  36559. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36560. }
  36561. if (this.uvs4) {
  36562. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36563. }
  36564. if (this.uvs5) {
  36565. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36566. }
  36567. if (this.uvs6) {
  36568. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36569. }
  36570. if (this.colors) {
  36571. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36572. }
  36573. if (this.matricesIndices) {
  36574. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36575. }
  36576. if (this.matricesWeights) {
  36577. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36578. }
  36579. if (this.matricesIndicesExtra) {
  36580. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36581. }
  36582. if (this.matricesWeightsExtra) {
  36583. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36584. }
  36585. if (this.indices) {
  36586. meshOrGeometry.setIndices(this.indices, null, updatable);
  36587. }
  36588. else {
  36589. meshOrGeometry.setIndices([], null);
  36590. }
  36591. return this;
  36592. };
  36593. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36594. if (this.positions) {
  36595. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36596. }
  36597. if (this.normals) {
  36598. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36599. }
  36600. if (this.tangents) {
  36601. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36602. }
  36603. if (this.uvs) {
  36604. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36605. }
  36606. if (this.uvs2) {
  36607. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36608. }
  36609. if (this.uvs3) {
  36610. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36611. }
  36612. if (this.uvs4) {
  36613. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36614. }
  36615. if (this.uvs5) {
  36616. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36617. }
  36618. if (this.uvs6) {
  36619. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36620. }
  36621. if (this.colors) {
  36622. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36623. }
  36624. if (this.matricesIndices) {
  36625. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36626. }
  36627. if (this.matricesWeights) {
  36628. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36629. }
  36630. if (this.matricesIndicesExtra) {
  36631. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36632. }
  36633. if (this.matricesWeightsExtra) {
  36634. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36635. }
  36636. if (this.indices) {
  36637. meshOrGeometry.setIndices(this.indices, null);
  36638. }
  36639. return this;
  36640. };
  36641. /**
  36642. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36643. * @param matrix the transforming matrix
  36644. * @returns the VertexData
  36645. */
  36646. VertexData.prototype.transform = function (matrix) {
  36647. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36648. var transformed = BABYLON.Vector3.Zero();
  36649. var index;
  36650. if (this.positions) {
  36651. var position = BABYLON.Vector3.Zero();
  36652. for (index = 0; index < this.positions.length; index += 3) {
  36653. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36654. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36655. this.positions[index] = transformed.x;
  36656. this.positions[index + 1] = transformed.y;
  36657. this.positions[index + 2] = transformed.z;
  36658. }
  36659. }
  36660. if (this.normals) {
  36661. var normal = BABYLON.Vector3.Zero();
  36662. for (index = 0; index < this.normals.length; index += 3) {
  36663. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36664. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36665. this.normals[index] = transformed.x;
  36666. this.normals[index + 1] = transformed.y;
  36667. this.normals[index + 2] = transformed.z;
  36668. }
  36669. }
  36670. if (this.tangents) {
  36671. var tangent = BABYLON.Vector4.Zero();
  36672. var tangentTransformed = BABYLON.Vector4.Zero();
  36673. for (index = 0; index < this.tangents.length; index += 4) {
  36674. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36675. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36676. this.tangents[index] = tangentTransformed.x;
  36677. this.tangents[index + 1] = tangentTransformed.y;
  36678. this.tangents[index + 2] = tangentTransformed.z;
  36679. this.tangents[index + 3] = tangentTransformed.w;
  36680. }
  36681. }
  36682. if (flip && this.indices) {
  36683. for (index = 0; index < this.indices.length; index += 3) {
  36684. var tmp = this.indices[index + 1];
  36685. this.indices[index + 1] = this.indices[index + 2];
  36686. this.indices[index + 2] = tmp;
  36687. }
  36688. }
  36689. return this;
  36690. };
  36691. /**
  36692. * Merges the passed VertexData into the current one
  36693. * @param other the VertexData to be merged into the current one
  36694. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36695. * @returns the modified VertexData
  36696. */
  36697. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36698. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36699. this._validate();
  36700. other._validate();
  36701. if (!this.normals !== !other.normals ||
  36702. !this.tangents !== !other.tangents ||
  36703. !this.uvs !== !other.uvs ||
  36704. !this.uvs2 !== !other.uvs2 ||
  36705. !this.uvs3 !== !other.uvs3 ||
  36706. !this.uvs4 !== !other.uvs4 ||
  36707. !this.uvs5 !== !other.uvs5 ||
  36708. !this.uvs6 !== !other.uvs6 ||
  36709. !this.colors !== !other.colors ||
  36710. !this.matricesIndices !== !other.matricesIndices ||
  36711. !this.matricesWeights !== !other.matricesWeights ||
  36712. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36713. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36714. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36715. }
  36716. if (other.indices) {
  36717. if (!this.indices) {
  36718. this.indices = [];
  36719. }
  36720. var offset = this.positions ? this.positions.length / 3 : 0;
  36721. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36722. if (isSrcTypedArray) {
  36723. var len = this.indices.length + other.indices.length;
  36724. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36725. temp.set(this.indices);
  36726. var decal = this.indices.length;
  36727. for (var index = 0; index < other.indices.length; index++) {
  36728. temp[decal + index] = other.indices[index] + offset;
  36729. }
  36730. this.indices = temp;
  36731. }
  36732. else {
  36733. for (var index = 0; index < other.indices.length; index++) {
  36734. this.indices.push(other.indices[index] + offset);
  36735. }
  36736. }
  36737. }
  36738. this.positions = this._mergeElement(this.positions, other.positions);
  36739. this.normals = this._mergeElement(this.normals, other.normals);
  36740. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36741. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36742. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36743. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36744. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36745. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36746. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36747. this.colors = this._mergeElement(this.colors, other.colors);
  36748. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36749. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36750. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36751. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36752. return this;
  36753. };
  36754. VertexData.prototype._mergeElement = function (source, other) {
  36755. if (!source) {
  36756. return other;
  36757. }
  36758. if (!other) {
  36759. return source;
  36760. }
  36761. var len = other.length + source.length;
  36762. var isSrcTypedArray = source instanceof Float32Array;
  36763. var isOthTypedArray = other instanceof Float32Array;
  36764. // use non-loop method when the source is Float32Array
  36765. if (isSrcTypedArray) {
  36766. var ret32 = new Float32Array(len);
  36767. ret32.set(source);
  36768. ret32.set(other, source.length);
  36769. return ret32;
  36770. // source is number[], when other is also use concat
  36771. }
  36772. else if (!isOthTypedArray) {
  36773. return source.concat(other);
  36774. // source is a number[], but other is a Float32Array, loop required
  36775. }
  36776. else {
  36777. var ret = source.slice(0); // copy source to a separate array
  36778. for (var i = 0, len = other.length; i < len; i++) {
  36779. ret.push(other[i]);
  36780. }
  36781. return ret;
  36782. }
  36783. };
  36784. VertexData.prototype._validate = function () {
  36785. if (!this.positions) {
  36786. throw new Error("Positions are required");
  36787. }
  36788. var getElementCount = function (kind, values) {
  36789. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36790. if ((values.length % stride) !== 0) {
  36791. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36792. }
  36793. return values.length / stride;
  36794. };
  36795. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36796. var validateElementCount = function (kind, values) {
  36797. var elementCount = getElementCount(kind, values);
  36798. if (elementCount !== positionsElementCount) {
  36799. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36800. }
  36801. };
  36802. if (this.normals)
  36803. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36804. if (this.tangents)
  36805. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36806. if (this.uvs)
  36807. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36808. if (this.uvs2)
  36809. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36810. if (this.uvs3)
  36811. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36812. if (this.uvs4)
  36813. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36814. if (this.uvs5)
  36815. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36816. if (this.uvs6)
  36817. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36818. if (this.colors)
  36819. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36820. if (this.matricesIndices)
  36821. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36822. if (this.matricesWeights)
  36823. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36824. if (this.matricesIndicesExtra)
  36825. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36826. if (this.matricesWeightsExtra)
  36827. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36828. };
  36829. /**
  36830. * Serializes the VertexData
  36831. * @returns a serialized object
  36832. */
  36833. VertexData.prototype.serialize = function () {
  36834. var serializationObject = this.serialize();
  36835. if (this.positions) {
  36836. serializationObject.positions = this.positions;
  36837. }
  36838. if (this.normals) {
  36839. serializationObject.normals = this.normals;
  36840. }
  36841. if (this.tangents) {
  36842. serializationObject.tangents = this.tangents;
  36843. }
  36844. if (this.uvs) {
  36845. serializationObject.uvs = this.uvs;
  36846. }
  36847. if (this.uvs2) {
  36848. serializationObject.uvs2 = this.uvs2;
  36849. }
  36850. if (this.uvs3) {
  36851. serializationObject.uvs3 = this.uvs3;
  36852. }
  36853. if (this.uvs4) {
  36854. serializationObject.uvs4 = this.uvs4;
  36855. }
  36856. if (this.uvs5) {
  36857. serializationObject.uvs5 = this.uvs5;
  36858. }
  36859. if (this.uvs6) {
  36860. serializationObject.uvs6 = this.uvs6;
  36861. }
  36862. if (this.colors) {
  36863. serializationObject.colors = this.colors;
  36864. }
  36865. if (this.matricesIndices) {
  36866. serializationObject.matricesIndices = this.matricesIndices;
  36867. serializationObject.matricesIndices._isExpanded = true;
  36868. }
  36869. if (this.matricesWeights) {
  36870. serializationObject.matricesWeights = this.matricesWeights;
  36871. }
  36872. if (this.matricesIndicesExtra) {
  36873. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36874. serializationObject.matricesIndicesExtra._isExpanded = true;
  36875. }
  36876. if (this.matricesWeightsExtra) {
  36877. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36878. }
  36879. serializationObject.indices = this.indices;
  36880. return serializationObject;
  36881. };
  36882. // Statics
  36883. /**
  36884. * Extracts the vertexData from a mesh
  36885. * @param mesh the mesh from which to extract the VertexData
  36886. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36887. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36888. * @returns the object VertexData associated to the passed mesh
  36889. */
  36890. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36891. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36892. };
  36893. /**
  36894. * Extracts the vertexData from the geometry
  36895. * @param geometry the geometry from which to extract the VertexData
  36896. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36897. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36898. * @returns the object VertexData associated to the passed mesh
  36899. */
  36900. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36901. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36902. };
  36903. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36904. var result = new VertexData();
  36905. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36906. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36907. }
  36908. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36909. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36910. }
  36911. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36912. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36913. }
  36914. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36915. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36916. }
  36917. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36918. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36919. }
  36920. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36921. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36922. }
  36923. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36924. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36925. }
  36926. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36927. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36928. }
  36929. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36930. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36931. }
  36932. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36933. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36934. }
  36935. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36936. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36937. }
  36938. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36939. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36940. }
  36941. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36942. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36943. }
  36944. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36945. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36946. }
  36947. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  36948. return result;
  36949. };
  36950. /**
  36951. * Creates the VertexData for a Ribbon
  36952. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36953. * * pathArray array of paths, each of which an array of successive Vector3
  36954. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36955. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36956. * * 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
  36957. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36958. * * 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)
  36959. * * 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)
  36960. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36961. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36962. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36963. * @returns the VertexData of the ribbon
  36964. */
  36965. VertexData.CreateRibbon = function (options) {
  36966. var pathArray = options.pathArray;
  36967. var closeArray = options.closeArray || false;
  36968. var closePath = options.closePath || false;
  36969. var invertUV = options.invertUV || false;
  36970. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36971. var offset = options.offset || defaultOffset;
  36972. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36973. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36974. var customUV = options.uvs;
  36975. var customColors = options.colors;
  36976. var positions = [];
  36977. var indices = [];
  36978. var normals = [];
  36979. var uvs = [];
  36980. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36981. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36982. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36983. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36984. var minlg; // minimal length among all paths from pathArray
  36985. var lg = []; // array of path lengths : nb of vertex per path
  36986. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36987. var p; // path iterator
  36988. var i; // point iterator
  36989. var j; // point iterator
  36990. // if single path in pathArray
  36991. if (pathArray.length < 2) {
  36992. var ar1 = [];
  36993. var ar2 = [];
  36994. for (i = 0; i < pathArray[0].length - offset; i++) {
  36995. ar1.push(pathArray[0][i]);
  36996. ar2.push(pathArray[0][i + offset]);
  36997. }
  36998. pathArray = [ar1, ar2];
  36999. }
  37000. // positions and horizontal distances (u)
  37001. var idc = 0;
  37002. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37003. var path;
  37004. var l;
  37005. minlg = pathArray[0].length;
  37006. var vectlg;
  37007. var dist;
  37008. for (p = 0; p < pathArray.length; p++) {
  37009. uTotalDistance[p] = 0;
  37010. us[p] = [0];
  37011. path = pathArray[p];
  37012. l = path.length;
  37013. minlg = (minlg < l) ? minlg : l;
  37014. j = 0;
  37015. while (j < l) {
  37016. positions.push(path[j].x, path[j].y, path[j].z);
  37017. if (j > 0) {
  37018. vectlg = path[j].subtract(path[j - 1]).length();
  37019. dist = vectlg + uTotalDistance[p];
  37020. us[p].push(dist);
  37021. uTotalDistance[p] = dist;
  37022. }
  37023. j++;
  37024. }
  37025. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37026. j--;
  37027. positions.push(path[0].x, path[0].y, path[0].z);
  37028. vectlg = path[j].subtract(path[0]).length();
  37029. dist = vectlg + uTotalDistance[p];
  37030. us[p].push(dist);
  37031. uTotalDistance[p] = dist;
  37032. }
  37033. lg[p] = l + closePathCorr;
  37034. idx[p] = idc;
  37035. idc += (l + closePathCorr);
  37036. }
  37037. // vertical distances (v)
  37038. var path1;
  37039. var path2;
  37040. var vertex1 = null;
  37041. var vertex2 = null;
  37042. for (i = 0; i < minlg + closePathCorr; i++) {
  37043. vTotalDistance[i] = 0;
  37044. vs[i] = [0];
  37045. for (p = 0; p < pathArray.length - 1; p++) {
  37046. path1 = pathArray[p];
  37047. path2 = pathArray[p + 1];
  37048. if (i === minlg) { // closePath
  37049. vertex1 = path1[0];
  37050. vertex2 = path2[0];
  37051. }
  37052. else {
  37053. vertex1 = path1[i];
  37054. vertex2 = path2[i];
  37055. }
  37056. vectlg = vertex2.subtract(vertex1).length();
  37057. dist = vectlg + vTotalDistance[i];
  37058. vs[i].push(dist);
  37059. vTotalDistance[i] = dist;
  37060. }
  37061. if (closeArray && vertex2 && vertex1) {
  37062. path1 = pathArray[p];
  37063. path2 = pathArray[0];
  37064. if (i === minlg) { // closePath
  37065. vertex2 = path2[0];
  37066. }
  37067. vectlg = vertex2.subtract(vertex1).length();
  37068. dist = vectlg + vTotalDistance[i];
  37069. vTotalDistance[i] = dist;
  37070. }
  37071. }
  37072. // uvs
  37073. var u;
  37074. var v;
  37075. if (customUV) {
  37076. for (p = 0; p < customUV.length; p++) {
  37077. uvs.push(customUV[p].x, customUV[p].y);
  37078. }
  37079. }
  37080. else {
  37081. for (p = 0; p < pathArray.length; p++) {
  37082. for (i = 0; i < minlg + closePathCorr; i++) {
  37083. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37084. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37085. if (invertUV) {
  37086. uvs.push(v, u);
  37087. }
  37088. else {
  37089. uvs.push(u, v);
  37090. }
  37091. }
  37092. }
  37093. }
  37094. // indices
  37095. p = 0; // path index
  37096. var pi = 0; // positions array index
  37097. var l1 = lg[p] - 1; // path1 length
  37098. var l2 = lg[p + 1] - 1; // path2 length
  37099. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37100. var shft = idx[1] - idx[0]; // shift
  37101. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37102. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37103. // 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
  37104. indices.push(pi, pi + shft, pi + 1);
  37105. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37106. pi += 1;
  37107. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37108. p++;
  37109. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37110. shft = idx[0] - idx[p];
  37111. l1 = lg[p] - 1;
  37112. l2 = lg[0] - 1;
  37113. }
  37114. else {
  37115. shft = idx[p + 1] - idx[p];
  37116. l1 = lg[p] - 1;
  37117. l2 = lg[p + 1] - 1;
  37118. }
  37119. pi = idx[p];
  37120. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37121. }
  37122. }
  37123. // normals
  37124. VertexData.ComputeNormals(positions, indices, normals);
  37125. if (closePath) { // update both the first and last vertex normals to their average value
  37126. var indexFirst = 0;
  37127. var indexLast = 0;
  37128. for (p = 0; p < pathArray.length; p++) {
  37129. indexFirst = idx[p] * 3;
  37130. if (p + 1 < pathArray.length) {
  37131. indexLast = (idx[p + 1] - 1) * 3;
  37132. }
  37133. else {
  37134. indexLast = normals.length - 3;
  37135. }
  37136. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37137. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37138. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37139. normals[indexLast] = normals[indexFirst];
  37140. normals[indexLast + 1] = normals[indexFirst + 1];
  37141. normals[indexLast + 2] = normals[indexFirst + 2];
  37142. }
  37143. }
  37144. // sides
  37145. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37146. // Colors
  37147. var colors = null;
  37148. if (customColors) {
  37149. colors = new Float32Array(customColors.length * 4);
  37150. for (var c = 0; c < customColors.length; c++) {
  37151. colors[c * 4] = customColors[c].r;
  37152. colors[c * 4 + 1] = customColors[c].g;
  37153. colors[c * 4 + 2] = customColors[c].b;
  37154. colors[c * 4 + 3] = customColors[c].a;
  37155. }
  37156. }
  37157. // Result
  37158. var vertexData = new VertexData();
  37159. var positions32 = new Float32Array(positions);
  37160. var normals32 = new Float32Array(normals);
  37161. var uvs32 = new Float32Array(uvs);
  37162. vertexData.indices = indices;
  37163. vertexData.positions = positions32;
  37164. vertexData.normals = normals32;
  37165. vertexData.uvs = uvs32;
  37166. if (colors) {
  37167. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37168. }
  37169. if (closePath) {
  37170. vertexData._idx = idx;
  37171. }
  37172. return vertexData;
  37173. };
  37174. /**
  37175. * Creates the VertexData for a box
  37176. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37177. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37178. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37179. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37180. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37181. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37182. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37183. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37184. * * 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)
  37185. * * 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)
  37186. * @returns the VertexData of the box
  37187. */
  37188. VertexData.CreateBox = function (options) {
  37189. var normalsSource = [
  37190. new BABYLON.Vector3(0, 0, 1),
  37191. new BABYLON.Vector3(0, 0, -1),
  37192. new BABYLON.Vector3(1, 0, 0),
  37193. new BABYLON.Vector3(-1, 0, 0),
  37194. new BABYLON.Vector3(0, 1, 0),
  37195. new BABYLON.Vector3(0, -1, 0)
  37196. ];
  37197. var indices = [];
  37198. var positions = [];
  37199. var normals = [];
  37200. var uvs = [];
  37201. var width = options.width || options.size || 1;
  37202. var height = options.height || options.size || 1;
  37203. var depth = options.depth || options.size || 1;
  37204. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37205. var faceUV = options.faceUV || new Array(6);
  37206. var faceColors = options.faceColors;
  37207. var colors = [];
  37208. // default face colors and UV if undefined
  37209. for (var f = 0; f < 6; f++) {
  37210. if (faceUV[f] === undefined) {
  37211. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37212. }
  37213. if (faceColors && faceColors[f] === undefined) {
  37214. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37215. }
  37216. }
  37217. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37218. // Create each face in turn.
  37219. for (var index = 0; index < normalsSource.length; index++) {
  37220. var normal = normalsSource[index];
  37221. // Get two vectors perpendicular to the face normal and to each other.
  37222. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37223. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37224. // Six indices (two triangles) per face.
  37225. var verticesLength = positions.length / 3;
  37226. indices.push(verticesLength);
  37227. indices.push(verticesLength + 1);
  37228. indices.push(verticesLength + 2);
  37229. indices.push(verticesLength);
  37230. indices.push(verticesLength + 2);
  37231. indices.push(verticesLength + 3);
  37232. // Four vertices per face.
  37233. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37234. positions.push(vertex.x, vertex.y, vertex.z);
  37235. normals.push(normal.x, normal.y, normal.z);
  37236. uvs.push(faceUV[index].z, faceUV[index].w);
  37237. if (faceColors) {
  37238. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37239. }
  37240. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37241. positions.push(vertex.x, vertex.y, vertex.z);
  37242. normals.push(normal.x, normal.y, normal.z);
  37243. uvs.push(faceUV[index].x, faceUV[index].w);
  37244. if (faceColors) {
  37245. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37246. }
  37247. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37248. positions.push(vertex.x, vertex.y, vertex.z);
  37249. normals.push(normal.x, normal.y, normal.z);
  37250. uvs.push(faceUV[index].x, faceUV[index].y);
  37251. if (faceColors) {
  37252. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37253. }
  37254. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37255. positions.push(vertex.x, vertex.y, vertex.z);
  37256. normals.push(normal.x, normal.y, normal.z);
  37257. uvs.push(faceUV[index].z, faceUV[index].y);
  37258. if (faceColors) {
  37259. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37260. }
  37261. }
  37262. // sides
  37263. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37264. // Result
  37265. var vertexData = new VertexData();
  37266. vertexData.indices = indices;
  37267. vertexData.positions = positions;
  37268. vertexData.normals = normals;
  37269. vertexData.uvs = uvs;
  37270. if (faceColors) {
  37271. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37272. vertexData.colors = totalColors;
  37273. }
  37274. return vertexData;
  37275. };
  37276. /**
  37277. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37278. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37279. * * segments sets the number of horizontal strips optional, default 32
  37280. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37281. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37282. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37283. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37284. * * 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
  37285. * * 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
  37286. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37287. * * 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)
  37288. * * 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)
  37289. * @returns the VertexData of the ellipsoid
  37290. */
  37291. VertexData.CreateSphere = function (options) {
  37292. var segments = options.segments || 32;
  37293. var diameterX = options.diameterX || options.diameter || 1;
  37294. var diameterY = options.diameterY || options.diameter || 1;
  37295. var diameterZ = options.diameterZ || options.diameter || 1;
  37296. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37297. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37298. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37299. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37300. var totalZRotationSteps = 2 + segments;
  37301. var totalYRotationSteps = 2 * totalZRotationSteps;
  37302. var indices = [];
  37303. var positions = [];
  37304. var normals = [];
  37305. var uvs = [];
  37306. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37307. var normalizedZ = zRotationStep / totalZRotationSteps;
  37308. var angleZ = normalizedZ * Math.PI * slice;
  37309. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37310. var normalizedY = yRotationStep / totalYRotationSteps;
  37311. var angleY = normalizedY * Math.PI * 2 * arc;
  37312. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37313. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37314. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37315. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37316. var vertex = complete.multiply(radius);
  37317. var normal = complete.divide(radius).normalize();
  37318. positions.push(vertex.x, vertex.y, vertex.z);
  37319. normals.push(normal.x, normal.y, normal.z);
  37320. uvs.push(normalizedY, normalizedZ);
  37321. }
  37322. if (zRotationStep > 0) {
  37323. var verticesCount = positions.length / 3;
  37324. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37325. indices.push((firstIndex));
  37326. indices.push((firstIndex + 1));
  37327. indices.push(firstIndex + totalYRotationSteps + 1);
  37328. indices.push((firstIndex + totalYRotationSteps + 1));
  37329. indices.push((firstIndex + 1));
  37330. indices.push((firstIndex + totalYRotationSteps + 2));
  37331. }
  37332. }
  37333. }
  37334. // Sides
  37335. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37336. // Result
  37337. var vertexData = new VertexData();
  37338. vertexData.indices = indices;
  37339. vertexData.positions = positions;
  37340. vertexData.normals = normals;
  37341. vertexData.uvs = uvs;
  37342. return vertexData;
  37343. };
  37344. /**
  37345. * Creates the VertexData for a cylinder, cone or prism
  37346. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37347. * * height sets the height (y direction) of the cylinder, optional, default 2
  37348. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37349. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37350. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37351. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37352. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37353. * * 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
  37354. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37355. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37356. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37357. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37358. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37359. * * 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)
  37360. * * 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)
  37361. * @returns the VertexData of the cylinder, cone or prism
  37362. */
  37363. VertexData.CreateCylinder = function (options) {
  37364. var height = options.height || 2;
  37365. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37366. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37367. var tessellation = options.tessellation || 24;
  37368. var subdivisions = options.subdivisions || 1;
  37369. var hasRings = options.hasRings ? true : false;
  37370. var enclose = options.enclose ? true : false;
  37371. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37372. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37373. var faceUV = options.faceUV || new Array(3);
  37374. var faceColors = options.faceColors;
  37375. // default face colors and UV if undefined
  37376. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37377. var ringNb = (hasRings) ? subdivisions : 1;
  37378. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37379. var f;
  37380. for (f = 0; f < surfaceNb; f++) {
  37381. if (faceColors && faceColors[f] === undefined) {
  37382. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37383. }
  37384. }
  37385. for (f = 0; f < surfaceNb; f++) {
  37386. if (faceUV && faceUV[f] === undefined) {
  37387. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37388. }
  37389. }
  37390. var indices = new Array();
  37391. var positions = new Array();
  37392. var normals = new Array();
  37393. var uvs = new Array();
  37394. var colors = new Array();
  37395. var angle_step = Math.PI * 2 * arc / tessellation;
  37396. var angle;
  37397. var h;
  37398. var radius;
  37399. var tan = (diameterBottom - diameterTop) / 2 / height;
  37400. var ringVertex = BABYLON.Vector3.Zero();
  37401. var ringNormal = BABYLON.Vector3.Zero();
  37402. var ringFirstVertex = BABYLON.Vector3.Zero();
  37403. var ringFirstNormal = BABYLON.Vector3.Zero();
  37404. var quadNormal = BABYLON.Vector3.Zero();
  37405. var Y = BABYLON.Axis.Y;
  37406. // positions, normals, uvs
  37407. var i;
  37408. var j;
  37409. var r;
  37410. var ringIdx = 1;
  37411. var s = 1; // surface index
  37412. var cs = 0;
  37413. var v = 0;
  37414. for (i = 0; i <= subdivisions; i++) {
  37415. h = i / subdivisions;
  37416. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37417. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37418. for (r = 0; r < ringIdx; r++) {
  37419. if (hasRings) {
  37420. s += r;
  37421. }
  37422. if (enclose) {
  37423. s += 2 * r;
  37424. }
  37425. for (j = 0; j <= tessellation; j++) {
  37426. angle = j * angle_step;
  37427. // position
  37428. ringVertex.x = Math.cos(-angle) * radius;
  37429. ringVertex.y = -height / 2 + h * height;
  37430. ringVertex.z = Math.sin(-angle) * radius;
  37431. // normal
  37432. if (diameterTop === 0 && i === subdivisions) {
  37433. // if no top cap, reuse former normals
  37434. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37435. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37436. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37437. }
  37438. else {
  37439. ringNormal.x = ringVertex.x;
  37440. ringNormal.z = ringVertex.z;
  37441. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37442. ringNormal.normalize();
  37443. }
  37444. // keep first ring vertex values for enclose
  37445. if (j === 0) {
  37446. ringFirstVertex.copyFrom(ringVertex);
  37447. ringFirstNormal.copyFrom(ringNormal);
  37448. }
  37449. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37450. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37451. if (hasRings) {
  37452. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37453. }
  37454. else {
  37455. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37456. }
  37457. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37458. if (faceColors) {
  37459. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37460. }
  37461. }
  37462. // if enclose, add four vertices and their dedicated normals
  37463. if (arc !== 1 && enclose) {
  37464. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37465. positions.push(0, ringVertex.y, 0);
  37466. positions.push(0, ringVertex.y, 0);
  37467. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37468. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37469. quadNormal.normalize();
  37470. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37471. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37472. quadNormal.normalize();
  37473. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37474. if (hasRings) {
  37475. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37476. }
  37477. else {
  37478. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37479. }
  37480. uvs.push(faceUV[s + 1].x, v);
  37481. uvs.push(faceUV[s + 1].z, v);
  37482. if (hasRings) {
  37483. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37484. }
  37485. else {
  37486. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37487. }
  37488. uvs.push(faceUV[s + 2].x, v);
  37489. uvs.push(faceUV[s + 2].z, v);
  37490. if (faceColors) {
  37491. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37492. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37493. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37494. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37495. }
  37496. }
  37497. if (cs !== s) {
  37498. cs = s;
  37499. }
  37500. }
  37501. }
  37502. // indices
  37503. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37504. var s;
  37505. i = 0;
  37506. for (s = 0; s < subdivisions; s++) {
  37507. var i0 = 0;
  37508. var i1 = 0;
  37509. var i2 = 0;
  37510. var i3 = 0;
  37511. for (j = 0; j < tessellation; j++) {
  37512. i0 = i * (e + 1) + j;
  37513. i1 = (i + 1) * (e + 1) + j;
  37514. i2 = i * (e + 1) + (j + 1);
  37515. i3 = (i + 1) * (e + 1) + (j + 1);
  37516. indices.push(i0, i1, i2);
  37517. indices.push(i3, i2, i1);
  37518. }
  37519. if (arc !== 1 && enclose) { // if enclose, add two quads
  37520. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37521. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37522. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37523. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37524. }
  37525. i = (hasRings) ? (i + 2) : (i + 1);
  37526. }
  37527. // Caps
  37528. var createCylinderCap = function (isTop) {
  37529. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37530. if (radius === 0) {
  37531. return;
  37532. }
  37533. // Cap positions, normals & uvs
  37534. var angle;
  37535. var circleVector;
  37536. var i;
  37537. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37538. var c = null;
  37539. if (faceColors) {
  37540. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37541. }
  37542. // cap center
  37543. var vbase = positions.length / 3;
  37544. var offset = isTop ? height / 2 : -height / 2;
  37545. var center = new BABYLON.Vector3(0, offset, 0);
  37546. positions.push(center.x, center.y, center.z);
  37547. normals.push(0, isTop ? 1 : -1, 0);
  37548. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37549. if (c) {
  37550. colors.push(c.r, c.g, c.b, c.a);
  37551. }
  37552. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37553. for (i = 0; i <= tessellation; i++) {
  37554. angle = Math.PI * 2 * i * arc / tessellation;
  37555. var cos = Math.cos(-angle);
  37556. var sin = Math.sin(-angle);
  37557. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37558. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37559. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37560. normals.push(0, isTop ? 1 : -1, 0);
  37561. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37562. if (c) {
  37563. colors.push(c.r, c.g, c.b, c.a);
  37564. }
  37565. }
  37566. // Cap indices
  37567. for (i = 0; i < tessellation; i++) {
  37568. if (!isTop) {
  37569. indices.push(vbase);
  37570. indices.push(vbase + (i + 1));
  37571. indices.push(vbase + (i + 2));
  37572. }
  37573. else {
  37574. indices.push(vbase);
  37575. indices.push(vbase + (i + 2));
  37576. indices.push(vbase + (i + 1));
  37577. }
  37578. }
  37579. };
  37580. // add caps to geometry
  37581. createCylinderCap(false);
  37582. createCylinderCap(true);
  37583. // Sides
  37584. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37585. var vertexData = new VertexData();
  37586. vertexData.indices = indices;
  37587. vertexData.positions = positions;
  37588. vertexData.normals = normals;
  37589. vertexData.uvs = uvs;
  37590. if (faceColors) {
  37591. vertexData.colors = colors;
  37592. }
  37593. return vertexData;
  37594. };
  37595. /**
  37596. * Creates the VertexData for a torus
  37597. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37598. * * diameter the diameter of the torus, optional default 1
  37599. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37600. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37601. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37602. * * 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)
  37603. * * 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)
  37604. * @returns the VertexData of the torus
  37605. */
  37606. VertexData.CreateTorus = function (options) {
  37607. var indices = [];
  37608. var positions = [];
  37609. var normals = [];
  37610. var uvs = [];
  37611. var diameter = options.diameter || 1;
  37612. var thickness = options.thickness || 0.5;
  37613. var tessellation = options.tessellation || 16;
  37614. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37615. var stride = tessellation + 1;
  37616. for (var i = 0; i <= tessellation; i++) {
  37617. var u = i / tessellation;
  37618. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37619. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37620. for (var j = 0; j <= tessellation; j++) {
  37621. var v = 1 - j / tessellation;
  37622. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37623. var dx = Math.cos(innerAngle);
  37624. var dy = Math.sin(innerAngle);
  37625. // Create a vertex.
  37626. var normal = new BABYLON.Vector3(dx, dy, 0);
  37627. var position = normal.scale(thickness / 2);
  37628. var textureCoordinate = new BABYLON.Vector2(u, v);
  37629. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37630. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37631. positions.push(position.x, position.y, position.z);
  37632. normals.push(normal.x, normal.y, normal.z);
  37633. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37634. // And create indices for two triangles.
  37635. var nextI = (i + 1) % stride;
  37636. var nextJ = (j + 1) % stride;
  37637. indices.push(i * stride + j);
  37638. indices.push(i * stride + nextJ);
  37639. indices.push(nextI * stride + j);
  37640. indices.push(i * stride + nextJ);
  37641. indices.push(nextI * stride + nextJ);
  37642. indices.push(nextI * stride + j);
  37643. }
  37644. }
  37645. // Sides
  37646. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37647. // Result
  37648. var vertexData = new VertexData();
  37649. vertexData.indices = indices;
  37650. vertexData.positions = positions;
  37651. vertexData.normals = normals;
  37652. vertexData.uvs = uvs;
  37653. return vertexData;
  37654. };
  37655. /**
  37656. * Creates the VertexData of the LineSystem
  37657. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37658. * - lines an array of lines, each line being an array of successive Vector3
  37659. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37660. * @returns the VertexData of the LineSystem
  37661. */
  37662. VertexData.CreateLineSystem = function (options) {
  37663. var indices = [];
  37664. var positions = [];
  37665. var lines = options.lines;
  37666. var colors = options.colors;
  37667. var vertexColors = [];
  37668. var idx = 0;
  37669. for (var l = 0; l < lines.length; l++) {
  37670. var points = lines[l];
  37671. for (var index = 0; index < points.length; index++) {
  37672. positions.push(points[index].x, points[index].y, points[index].z);
  37673. if (colors) {
  37674. var color = colors[l];
  37675. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37676. }
  37677. if (index > 0) {
  37678. indices.push(idx - 1);
  37679. indices.push(idx);
  37680. }
  37681. idx++;
  37682. }
  37683. }
  37684. var vertexData = new VertexData();
  37685. vertexData.indices = indices;
  37686. vertexData.positions = positions;
  37687. if (colors) {
  37688. vertexData.colors = vertexColors;
  37689. }
  37690. return vertexData;
  37691. };
  37692. /**
  37693. * Create the VertexData for a DashedLines
  37694. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37695. * - points an array successive Vector3
  37696. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37697. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37698. * - dashNb the intended total number of dashes, optional, default 200
  37699. * @returns the VertexData for the DashedLines
  37700. */
  37701. VertexData.CreateDashedLines = function (options) {
  37702. var dashSize = options.dashSize || 3;
  37703. var gapSize = options.gapSize || 1;
  37704. var dashNb = options.dashNb || 200;
  37705. var points = options.points;
  37706. var positions = new Array();
  37707. var indices = new Array();
  37708. var curvect = BABYLON.Vector3.Zero();
  37709. var lg = 0;
  37710. var nb = 0;
  37711. var shft = 0;
  37712. var dashshft = 0;
  37713. var curshft = 0;
  37714. var idx = 0;
  37715. var i = 0;
  37716. for (i = 0; i < points.length - 1; i++) {
  37717. points[i + 1].subtractToRef(points[i], curvect);
  37718. lg += curvect.length();
  37719. }
  37720. shft = lg / dashNb;
  37721. dashshft = dashSize * shft / (dashSize + gapSize);
  37722. for (i = 0; i < points.length - 1; i++) {
  37723. points[i + 1].subtractToRef(points[i], curvect);
  37724. nb = Math.floor(curvect.length() / shft);
  37725. curvect.normalize();
  37726. for (var j = 0; j < nb; j++) {
  37727. curshft = shft * j;
  37728. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37729. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37730. indices.push(idx, idx + 1);
  37731. idx += 2;
  37732. }
  37733. }
  37734. // Result
  37735. var vertexData = new VertexData();
  37736. vertexData.positions = positions;
  37737. vertexData.indices = indices;
  37738. return vertexData;
  37739. };
  37740. /**
  37741. * Creates the VertexData for a Ground
  37742. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37743. * - width the width (x direction) of the ground, optional, default 1
  37744. * - height the height (z direction) of the ground, optional, default 1
  37745. * - subdivisions the number of subdivisions per side, optional, default 1
  37746. * @returns the VertexData of the Ground
  37747. */
  37748. VertexData.CreateGround = function (options) {
  37749. var indices = [];
  37750. var positions = [];
  37751. var normals = [];
  37752. var uvs = [];
  37753. var row, col;
  37754. var width = options.width || 1;
  37755. var height = options.height || 1;
  37756. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37757. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37758. for (row = 0; row <= subdivisionsY; row++) {
  37759. for (col = 0; col <= subdivisionsX; col++) {
  37760. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37761. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37762. positions.push(position.x, position.y, position.z);
  37763. normals.push(normal.x, normal.y, normal.z);
  37764. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37765. }
  37766. }
  37767. for (row = 0; row < subdivisionsY; row++) {
  37768. for (col = 0; col < subdivisionsX; col++) {
  37769. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37770. indices.push(col + 1 + row * (subdivisionsX + 1));
  37771. indices.push(col + row * (subdivisionsX + 1));
  37772. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37773. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37774. indices.push(col + row * (subdivisionsX + 1));
  37775. }
  37776. }
  37777. // Result
  37778. var vertexData = new VertexData();
  37779. vertexData.indices = indices;
  37780. vertexData.positions = positions;
  37781. vertexData.normals = normals;
  37782. vertexData.uvs = uvs;
  37783. return vertexData;
  37784. };
  37785. /**
  37786. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37787. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37788. * * xmin the ground minimum X coordinate, optional, default -1
  37789. * * zmin the ground minimum Z coordinate, optional, default -1
  37790. * * xmax the ground maximum X coordinate, optional, default 1
  37791. * * zmax the ground maximum Z coordinate, optional, default 1
  37792. * * 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}
  37793. * * 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}
  37794. * @returns the VertexData of the TiledGround
  37795. */
  37796. VertexData.CreateTiledGround = function (options) {
  37797. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37798. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37799. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37800. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37801. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37802. var precision = options.precision || { w: 1, h: 1 };
  37803. var indices = new Array();
  37804. var positions = new Array();
  37805. var normals = new Array();
  37806. var uvs = new Array();
  37807. var row, col, tileRow, tileCol;
  37808. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37809. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37810. precision.w = (precision.w < 1) ? 1 : precision.w;
  37811. precision.h = (precision.h < 1) ? 1 : precision.h;
  37812. var tileSize = {
  37813. 'w': (xmax - xmin) / subdivisions.w,
  37814. 'h': (zmax - zmin) / subdivisions.h
  37815. };
  37816. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37817. // Indices
  37818. var base = positions.length / 3;
  37819. var rowLength = precision.w + 1;
  37820. for (row = 0; row < precision.h; row++) {
  37821. for (col = 0; col < precision.w; col++) {
  37822. var square = [
  37823. base + col + row * rowLength,
  37824. base + (col + 1) + row * rowLength,
  37825. base + (col + 1) + (row + 1) * rowLength,
  37826. base + col + (row + 1) * rowLength
  37827. ];
  37828. indices.push(square[1]);
  37829. indices.push(square[2]);
  37830. indices.push(square[3]);
  37831. indices.push(square[0]);
  37832. indices.push(square[1]);
  37833. indices.push(square[3]);
  37834. }
  37835. }
  37836. // Position, normals and uvs
  37837. var position = BABYLON.Vector3.Zero();
  37838. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37839. for (row = 0; row <= precision.h; row++) {
  37840. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37841. for (col = 0; col <= precision.w; col++) {
  37842. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37843. position.y = 0;
  37844. positions.push(position.x, position.y, position.z);
  37845. normals.push(normal.x, normal.y, normal.z);
  37846. uvs.push(col / precision.w, row / precision.h);
  37847. }
  37848. }
  37849. }
  37850. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37851. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37852. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37853. }
  37854. }
  37855. // Result
  37856. var vertexData = new VertexData();
  37857. vertexData.indices = indices;
  37858. vertexData.positions = positions;
  37859. vertexData.normals = normals;
  37860. vertexData.uvs = uvs;
  37861. return vertexData;
  37862. };
  37863. /**
  37864. * Creates the VertexData of the Ground designed from a heightmap
  37865. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37866. * * width the width (x direction) of the ground
  37867. * * height the height (z direction) of the ground
  37868. * * subdivisions the number of subdivisions per side
  37869. * * minHeight the minimum altitude on the ground, optional, default 0
  37870. * * maxHeight the maximum altitude on the ground, optional default 1
  37871. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37872. * * buffer the array holding the image color data
  37873. * * bufferWidth the width of image
  37874. * * bufferHeight the height of image
  37875. * @returns the VertexData of the Ground designed from a heightmap
  37876. */
  37877. VertexData.CreateGroundFromHeightMap = function (options) {
  37878. var indices = [];
  37879. var positions = [];
  37880. var normals = [];
  37881. var uvs = [];
  37882. var row, col;
  37883. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37884. // Vertices
  37885. for (row = 0; row <= options.subdivisions; row++) {
  37886. for (col = 0; col <= options.subdivisions; col++) {
  37887. 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));
  37888. // Compute height
  37889. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37890. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37891. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37892. var r = options.buffer[pos] / 255.0;
  37893. var g = options.buffer[pos + 1] / 255.0;
  37894. var b = options.buffer[pos + 2] / 255.0;
  37895. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37896. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37897. // Add vertex
  37898. positions.push(position.x, position.y, position.z);
  37899. normals.push(0, 0, 0);
  37900. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37901. }
  37902. }
  37903. // Indices
  37904. for (row = 0; row < options.subdivisions; row++) {
  37905. for (col = 0; col < options.subdivisions; col++) {
  37906. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37907. indices.push(col + 1 + row * (options.subdivisions + 1));
  37908. indices.push(col + row * (options.subdivisions + 1));
  37909. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37910. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37911. indices.push(col + row * (options.subdivisions + 1));
  37912. }
  37913. }
  37914. // Normals
  37915. VertexData.ComputeNormals(positions, indices, normals);
  37916. // Result
  37917. var vertexData = new VertexData();
  37918. vertexData.indices = indices;
  37919. vertexData.positions = positions;
  37920. vertexData.normals = normals;
  37921. vertexData.uvs = uvs;
  37922. return vertexData;
  37923. };
  37924. /**
  37925. * Creates the VertexData for a Plane
  37926. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37927. * * size sets the width and height of the plane to the value of size, optional default 1
  37928. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37929. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37930. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37931. * * 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)
  37932. * * 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)
  37933. * @returns the VertexData of the box
  37934. */
  37935. VertexData.CreatePlane = function (options) {
  37936. var indices = [];
  37937. var positions = [];
  37938. var normals = [];
  37939. var uvs = [];
  37940. var width = options.width || options.size || 1;
  37941. var height = options.height || options.size || 1;
  37942. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37943. // Vertices
  37944. var halfWidth = width / 2.0;
  37945. var halfHeight = height / 2.0;
  37946. positions.push(-halfWidth, -halfHeight, 0);
  37947. normals.push(0, 0, -1.0);
  37948. uvs.push(0.0, 0.0);
  37949. positions.push(halfWidth, -halfHeight, 0);
  37950. normals.push(0, 0, -1.0);
  37951. uvs.push(1.0, 0.0);
  37952. positions.push(halfWidth, halfHeight, 0);
  37953. normals.push(0, 0, -1.0);
  37954. uvs.push(1.0, 1.0);
  37955. positions.push(-halfWidth, halfHeight, 0);
  37956. normals.push(0, 0, -1.0);
  37957. uvs.push(0.0, 1.0);
  37958. // Indices
  37959. indices.push(0);
  37960. indices.push(1);
  37961. indices.push(2);
  37962. indices.push(0);
  37963. indices.push(2);
  37964. indices.push(3);
  37965. // Sides
  37966. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37967. // Result
  37968. var vertexData = new VertexData();
  37969. vertexData.indices = indices;
  37970. vertexData.positions = positions;
  37971. vertexData.normals = normals;
  37972. vertexData.uvs = uvs;
  37973. return vertexData;
  37974. };
  37975. /**
  37976. * Creates the VertexData of the Disc or regular Polygon
  37977. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37978. * * radius the radius of the disc, optional default 0.5
  37979. * * tessellation the number of polygon sides, optional, default 64
  37980. * * 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
  37981. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37982. * * 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)
  37983. * * 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)
  37984. * @returns the VertexData of the box
  37985. */
  37986. VertexData.CreateDisc = function (options) {
  37987. var positions = new Array();
  37988. var indices = new Array();
  37989. var normals = new Array();
  37990. var uvs = new Array();
  37991. var radius = options.radius || 0.5;
  37992. var tessellation = options.tessellation || 64;
  37993. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37994. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37995. // positions and uvs
  37996. positions.push(0, 0, 0); // disc center first
  37997. uvs.push(0.5, 0.5);
  37998. var theta = Math.PI * 2 * arc;
  37999. var step = theta / tessellation;
  38000. for (var a = 0; a < theta; a += step) {
  38001. var x = Math.cos(a);
  38002. var y = Math.sin(a);
  38003. var u = (x + 1) / 2;
  38004. var v = (1 - y) / 2;
  38005. positions.push(radius * x, radius * y, 0);
  38006. uvs.push(u, v);
  38007. }
  38008. if (arc === 1) {
  38009. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38010. uvs.push(uvs[2], uvs[3]);
  38011. }
  38012. //indices
  38013. var vertexNb = positions.length / 3;
  38014. for (var i = 1; i < vertexNb - 1; i++) {
  38015. indices.push(i + 1, 0, i);
  38016. }
  38017. // result
  38018. VertexData.ComputeNormals(positions, indices, normals);
  38019. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38020. var vertexData = new VertexData();
  38021. vertexData.indices = indices;
  38022. vertexData.positions = positions;
  38023. vertexData.normals = normals;
  38024. vertexData.uvs = uvs;
  38025. return vertexData;
  38026. };
  38027. /**
  38028. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38029. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38030. * @param polygon a mesh built from polygonTriangulation.build()
  38031. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38032. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38033. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38034. * @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)
  38035. * @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)
  38036. * @returns the VertexData of the Polygon
  38037. */
  38038. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38039. var faceUV = fUV || new Array(3);
  38040. var faceColors = fColors;
  38041. var colors = [];
  38042. // default face colors and UV if undefined
  38043. for (var f = 0; f < 3; f++) {
  38044. if (faceUV[f] === undefined) {
  38045. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38046. }
  38047. if (faceColors && faceColors[f] === undefined) {
  38048. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38049. }
  38050. }
  38051. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38052. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38053. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38054. var indices = polygon.getIndices();
  38055. // set face colours and textures
  38056. var idx = 0;
  38057. var face = 0;
  38058. for (var index = 0; index < normals.length; index += 3) {
  38059. //Edge Face no. 1
  38060. if (Math.abs(normals[index + 1]) < 0.001) {
  38061. face = 1;
  38062. }
  38063. //Top Face no. 0
  38064. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38065. face = 0;
  38066. }
  38067. //Bottom Face no. 2
  38068. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38069. face = 2;
  38070. }
  38071. idx = index / 3;
  38072. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38073. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38074. if (faceColors) {
  38075. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38076. }
  38077. }
  38078. // sides
  38079. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38080. // Result
  38081. var vertexData = new VertexData();
  38082. vertexData.indices = indices;
  38083. vertexData.positions = positions;
  38084. vertexData.normals = normals;
  38085. vertexData.uvs = uvs;
  38086. if (faceColors) {
  38087. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38088. vertexData.colors = totalColors;
  38089. }
  38090. return vertexData;
  38091. };
  38092. /**
  38093. * Creates the VertexData of the IcoSphere
  38094. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38095. * * radius the radius of the IcoSphere, optional default 1
  38096. * * radiusX allows stretching in the x direction, optional, default radius
  38097. * * radiusY allows stretching in the y direction, optional, default radius
  38098. * * radiusZ allows stretching in the z direction, optional, default radius
  38099. * * flat when true creates a flat shaded mesh, optional, default true
  38100. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38101. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38102. * * 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)
  38103. * * 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)
  38104. * @returns the VertexData of the IcoSphere
  38105. */
  38106. VertexData.CreateIcoSphere = function (options) {
  38107. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38108. var radius = options.radius || 1;
  38109. var flat = (options.flat === undefined) ? true : options.flat;
  38110. var subdivisions = options.subdivisions || 4;
  38111. var radiusX = options.radiusX || radius;
  38112. var radiusY = options.radiusY || radius;
  38113. var radiusZ = options.radiusZ || radius;
  38114. var t = (1 + Math.sqrt(5)) / 2;
  38115. // 12 vertex x,y,z
  38116. var ico_vertices = [
  38117. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38118. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38119. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38120. ];
  38121. // index of 3 vertex makes a face of icopshere
  38122. var ico_indices = [
  38123. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38124. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38125. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38126. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38127. ];
  38128. // vertex for uv have aliased position, not for UV
  38129. var vertices_unalias_id = [
  38130. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38131. // vertex alias
  38132. 0,
  38133. 2,
  38134. 3,
  38135. 3,
  38136. 3,
  38137. 4,
  38138. 7,
  38139. 8,
  38140. 9,
  38141. 9,
  38142. 10,
  38143. 11 // 23: B + 12
  38144. ];
  38145. // uv as integer step (not pixels !)
  38146. var ico_vertexuv = [
  38147. 5, 1, 3, 1, 6, 4, 0, 0,
  38148. 5, 3, 4, 2, 2, 2, 4, 0,
  38149. 2, 0, 1, 1, 6, 0, 6, 2,
  38150. // vertex alias (for same vertex on different faces)
  38151. 0, 4,
  38152. 3, 3,
  38153. 4, 4,
  38154. 3, 1,
  38155. 4, 2,
  38156. 4, 4,
  38157. 0, 2,
  38158. 1, 1,
  38159. 2, 2,
  38160. 3, 3,
  38161. 1, 3,
  38162. 2, 4 // 23: B + 12
  38163. ];
  38164. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38165. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38166. // First island of uv mapping
  38167. // v = 4h 3+ 2
  38168. // v = 3h 9+ 4
  38169. // v = 2h 9+ 5 B
  38170. // v = 1h 9 1 0
  38171. // v = 0h 3 8 7 A
  38172. // u = 0 1 2 3 4 5 6 *a
  38173. // Second island of uv mapping
  38174. // v = 4h 0+ B+ 4+
  38175. // v = 3h A+ 2+
  38176. // v = 2h 7+ 6 3+
  38177. // v = 1h 8+ 3+
  38178. // v = 0h
  38179. // u = 0 1 2 3 4 5 6 *a
  38180. // Face layout on texture UV mapping
  38181. // ============
  38182. // \ 4 /\ 16 / ======
  38183. // \ / \ / /\ 11 /
  38184. // \/ 7 \/ / \ /
  38185. // ======= / 10 \/
  38186. // /\ 17 /\ =======
  38187. // / \ / \ \ 15 /\
  38188. // / 8 \/ 12 \ \ / \
  38189. // ============ \/ 6 \
  38190. // \ 18 /\ ============
  38191. // \ / \ \ 5 /\ 0 /
  38192. // \/ 13 \ \ / \ /
  38193. // ======= \/ 1 \/
  38194. // =============
  38195. // /\ 19 /\ 2 /\
  38196. // / \ / \ / \
  38197. // / 14 \/ 9 \/ 3 \
  38198. // ===================
  38199. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38200. var ustep = 138 / 1024;
  38201. var vstep = 239 / 1024;
  38202. var uoffset = 60 / 1024;
  38203. var voffset = 26 / 1024;
  38204. // Second island should have margin, not to touch the first island
  38205. // avoid any borderline artefact in pixel rounding
  38206. var island_u_offset = -40 / 1024;
  38207. var island_v_offset = +20 / 1024;
  38208. // face is either island 0 or 1 :
  38209. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38210. var island = [
  38211. 0, 0, 0, 0, 1,
  38212. 0, 0, 1, 1, 0,
  38213. 0, 0, 1, 1, 0,
  38214. 0, 1, 1, 1, 0 // 15 - 19
  38215. ];
  38216. var indices = new Array();
  38217. var positions = new Array();
  38218. var normals = new Array();
  38219. var uvs = new Array();
  38220. var current_indice = 0;
  38221. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38222. var face_vertex_pos = new Array(3);
  38223. var face_vertex_uv = new Array(3);
  38224. var v012;
  38225. for (v012 = 0; v012 < 3; v012++) {
  38226. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38227. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38228. }
  38229. // create all with normals
  38230. for (var face = 0; face < 20; face++) {
  38231. // 3 vertex per face
  38232. for (v012 = 0; v012 < 3; v012++) {
  38233. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38234. var v_id = ico_indices[3 * face + v012];
  38235. // vertex have 3D position (x,y,z)
  38236. 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]);
  38237. // Normalize to get normal, then scale to radius
  38238. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38239. // uv Coordinates from vertex ID
  38240. 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);
  38241. }
  38242. // Subdivide the face (interpolate pos, norm, uv)
  38243. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38244. // - norm is linear interpolation of vertex corner normal
  38245. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38246. // - uv is linear interpolation
  38247. //
  38248. // Topology is as below for sub-divide by 2
  38249. // vertex shown as v0,v1,v2
  38250. // interp index is i1 to progress in range [v0,v1[
  38251. // interp index is i2 to progress in range [v0,v2[
  38252. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38253. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38254. //
  38255. //
  38256. // i2 v2
  38257. // ^ ^
  38258. // / / \
  38259. // / / \
  38260. // / / \
  38261. // / / (0,1) \
  38262. // / #---------\
  38263. // / / \ (0,0)'/ \
  38264. // / / \ / \
  38265. // / / \ / \
  38266. // / / (0,0) \ / (1,0) \
  38267. // / #---------#---------\
  38268. // v0 v1
  38269. //
  38270. // --------------------> i1
  38271. //
  38272. // interp of (i1,i2):
  38273. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38274. // along i1 : lerp(x0,x1, i1/(S-i2))
  38275. //
  38276. // centroid of triangle is needed to get help normal computation
  38277. // (c1,c2) are used for centroid location
  38278. var interp_vertex = function (i1, i2, c1, c2) {
  38279. // vertex is interpolated from
  38280. // - face_vertex_pos[0..2]
  38281. // - face_vertex_uv[0..2]
  38282. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38283. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38284. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38285. pos_interp.normalize();
  38286. var vertex_normal;
  38287. if (flat) {
  38288. // in flat mode, recalculate normal as face centroid normal
  38289. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38290. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38291. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38292. }
  38293. else {
  38294. // in smooth mode, recalculate normal from each single vertex position
  38295. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38296. }
  38297. // Vertex normal need correction due to X,Y,Z radius scaling
  38298. vertex_normal.x /= radiusX;
  38299. vertex_normal.y /= radiusY;
  38300. vertex_normal.z /= radiusZ;
  38301. vertex_normal.normalize();
  38302. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38303. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38304. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38305. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38306. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38307. uvs.push(uv_interp.x, uv_interp.y);
  38308. // push each vertex has member of a face
  38309. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38310. indices.push(current_indice);
  38311. current_indice++;
  38312. };
  38313. for (var i2 = 0; i2 < subdivisions; i2++) {
  38314. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38315. // face : (i1,i2) for /\ :
  38316. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38317. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38318. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38319. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38320. if (i1 + i2 + 1 < subdivisions) {
  38321. // face : (i1,i2)' for \/ :
  38322. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38323. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38324. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38325. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38326. }
  38327. }
  38328. }
  38329. }
  38330. // Sides
  38331. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38332. // Result
  38333. var vertexData = new VertexData();
  38334. vertexData.indices = indices;
  38335. vertexData.positions = positions;
  38336. vertexData.normals = normals;
  38337. vertexData.uvs = uvs;
  38338. return vertexData;
  38339. };
  38340. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38341. /**
  38342. * Creates the VertexData for a Polyhedron
  38343. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38344. * * type provided types are:
  38345. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38346. * * 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)
  38347. * * size the size of the IcoSphere, optional default 1
  38348. * * sizeX allows stretching in the x direction, optional, default size
  38349. * * sizeY allows stretching in the y direction, optional, default size
  38350. * * sizeZ allows stretching in the z direction, optional, default size
  38351. * * 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
  38352. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38353. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38354. * * flat when true creates a flat shaded mesh, optional, default true
  38355. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38356. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38357. * * 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)
  38358. * * 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)
  38359. * @returns the VertexData of the Polyhedron
  38360. */
  38361. VertexData.CreatePolyhedron = function (options) {
  38362. // provided polyhedron types :
  38363. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38364. // 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)
  38365. var polyhedra = [];
  38366. 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]] };
  38367. 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]] };
  38368. polyhedra[2] = {
  38369. 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]],
  38370. 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]]
  38371. };
  38372. polyhedra[3] = {
  38373. 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]],
  38374. 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]]
  38375. };
  38376. polyhedra[4] = {
  38377. 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]],
  38378. 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]]
  38379. };
  38380. 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]] };
  38381. 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]] };
  38382. 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]] };
  38383. 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]] };
  38384. 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]] };
  38385. 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]] };
  38386. 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]] };
  38387. 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]] };
  38388. 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]] };
  38389. polyhedra[14] = {
  38390. 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]],
  38391. 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]]
  38392. };
  38393. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38394. var size = options.size;
  38395. var sizeX = options.sizeX || size || 1;
  38396. var sizeY = options.sizeY || size || 1;
  38397. var sizeZ = options.sizeZ || size || 1;
  38398. var data = options.custom || polyhedra[type];
  38399. var nbfaces = data.face.length;
  38400. var faceUV = options.faceUV || new Array(nbfaces);
  38401. var faceColors = options.faceColors;
  38402. var flat = (options.flat === undefined) ? true : options.flat;
  38403. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38404. var positions = new Array();
  38405. var indices = new Array();
  38406. var normals = new Array();
  38407. var uvs = new Array();
  38408. var colors = new Array();
  38409. var index = 0;
  38410. var faceIdx = 0; // face cursor in the array "indexes"
  38411. var indexes = new Array();
  38412. var i = 0;
  38413. var f = 0;
  38414. var u, v, ang, x, y, tmp;
  38415. // default face colors and UV if undefined
  38416. if (flat) {
  38417. for (f = 0; f < nbfaces; f++) {
  38418. if (faceColors && faceColors[f] === undefined) {
  38419. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38420. }
  38421. if (faceUV && faceUV[f] === undefined) {
  38422. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38423. }
  38424. }
  38425. }
  38426. if (!flat) {
  38427. for (i = 0; i < data.vertex.length; i++) {
  38428. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38429. uvs.push(0, 0);
  38430. }
  38431. for (f = 0; f < nbfaces; f++) {
  38432. for (i = 0; i < data.face[f].length - 2; i++) {
  38433. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38434. }
  38435. }
  38436. }
  38437. else {
  38438. for (f = 0; f < nbfaces; f++) {
  38439. var fl = data.face[f].length; // number of vertices of the current face
  38440. ang = 2 * Math.PI / fl;
  38441. x = 0.5 * Math.tan(ang / 2);
  38442. y = 0.5;
  38443. // positions, uvs, colors
  38444. for (i = 0; i < fl; i++) {
  38445. // positions
  38446. 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);
  38447. indexes.push(index);
  38448. index++;
  38449. // uvs
  38450. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38451. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38452. uvs.push(u, v);
  38453. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38454. y = x * Math.sin(ang) + y * Math.cos(ang);
  38455. x = tmp;
  38456. // colors
  38457. if (faceColors) {
  38458. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38459. }
  38460. }
  38461. // indices from indexes
  38462. for (i = 0; i < fl - 2; i++) {
  38463. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38464. }
  38465. faceIdx += fl;
  38466. }
  38467. }
  38468. VertexData.ComputeNormals(positions, indices, normals);
  38469. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38470. var vertexData = new VertexData();
  38471. vertexData.positions = positions;
  38472. vertexData.indices = indices;
  38473. vertexData.normals = normals;
  38474. vertexData.uvs = uvs;
  38475. if (faceColors && flat) {
  38476. vertexData.colors = colors;
  38477. }
  38478. return vertexData;
  38479. };
  38480. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38481. /**
  38482. * Creates the VertexData for a TorusKnot
  38483. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38484. * * radius the radius of the torus knot, optional, default 2
  38485. * * tube the thickness of the tube, optional, default 0.5
  38486. * * radialSegments the number of sides on each tube segments, optional, default 32
  38487. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38488. * * p the number of windings around the z axis, optional, default 2
  38489. * * q the number of windings around the x axis, optional, default 3
  38490. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38491. * * 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)
  38492. * * 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)
  38493. * @returns the VertexData of the Torus Knot
  38494. */
  38495. VertexData.CreateTorusKnot = function (options) {
  38496. var indices = new Array();
  38497. var positions = new Array();
  38498. var normals = new Array();
  38499. var uvs = new Array();
  38500. var radius = options.radius || 2;
  38501. var tube = options.tube || 0.5;
  38502. var radialSegments = options.radialSegments || 32;
  38503. var tubularSegments = options.tubularSegments || 32;
  38504. var p = options.p || 2;
  38505. var q = options.q || 3;
  38506. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38507. // Helper
  38508. var getPos = function (angle) {
  38509. var cu = Math.cos(angle);
  38510. var su = Math.sin(angle);
  38511. var quOverP = q / p * angle;
  38512. var cs = Math.cos(quOverP);
  38513. var tx = radius * (2 + cs) * 0.5 * cu;
  38514. var ty = radius * (2 + cs) * su * 0.5;
  38515. var tz = radius * Math.sin(quOverP) * 0.5;
  38516. return new BABYLON.Vector3(tx, ty, tz);
  38517. };
  38518. // Vertices
  38519. var i;
  38520. var j;
  38521. for (i = 0; i <= radialSegments; i++) {
  38522. var modI = i % radialSegments;
  38523. var u = modI / radialSegments * 2 * p * Math.PI;
  38524. var p1 = getPos(u);
  38525. var p2 = getPos(u + 0.01);
  38526. var tang = p2.subtract(p1);
  38527. var n = p2.add(p1);
  38528. var bitan = BABYLON.Vector3.Cross(tang, n);
  38529. n = BABYLON.Vector3.Cross(bitan, tang);
  38530. bitan.normalize();
  38531. n.normalize();
  38532. for (j = 0; j < tubularSegments; j++) {
  38533. var modJ = j % tubularSegments;
  38534. var v = modJ / tubularSegments * 2 * Math.PI;
  38535. var cx = -tube * Math.cos(v);
  38536. var cy = tube * Math.sin(v);
  38537. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38538. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38539. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38540. uvs.push(i / radialSegments);
  38541. uvs.push(j / tubularSegments);
  38542. }
  38543. }
  38544. for (i = 0; i < radialSegments; i++) {
  38545. for (j = 0; j < tubularSegments; j++) {
  38546. var jNext = (j + 1) % tubularSegments;
  38547. var a = i * tubularSegments + j;
  38548. var b = (i + 1) * tubularSegments + j;
  38549. var c = (i + 1) * tubularSegments + jNext;
  38550. var d = i * tubularSegments + jNext;
  38551. indices.push(d);
  38552. indices.push(b);
  38553. indices.push(a);
  38554. indices.push(d);
  38555. indices.push(c);
  38556. indices.push(b);
  38557. }
  38558. }
  38559. // Normals
  38560. VertexData.ComputeNormals(positions, indices, normals);
  38561. // Sides
  38562. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38563. // Result
  38564. var vertexData = new VertexData();
  38565. vertexData.indices = indices;
  38566. vertexData.positions = positions;
  38567. vertexData.normals = normals;
  38568. vertexData.uvs = uvs;
  38569. return vertexData;
  38570. };
  38571. // Tools
  38572. /**
  38573. * Compute normals for given positions and indices
  38574. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38575. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38576. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38577. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38578. * * facetNormals : optional array of facet normals (vector3)
  38579. * * facetPositions : optional array of facet positions (vector3)
  38580. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38581. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38582. * * bInfo : optional bounding info, required for facetPartitioning computation
  38583. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38584. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38585. * * useRightHandedSystem: optional boolean to for right handed system computation
  38586. * * depthSort : optional boolean to enable the facet depth sort computation
  38587. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38588. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38589. */
  38590. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38591. // temporary scalar variables
  38592. var index = 0; // facet index
  38593. var p1p2x = 0.0; // p1p2 vector x coordinate
  38594. var p1p2y = 0.0; // p1p2 vector y coordinate
  38595. var p1p2z = 0.0; // p1p2 vector z coordinate
  38596. var p3p2x = 0.0; // p3p2 vector x coordinate
  38597. var p3p2y = 0.0; // p3p2 vector y coordinate
  38598. var p3p2z = 0.0; // p3p2 vector z coordinate
  38599. var faceNormalx = 0.0; // facet normal x coordinate
  38600. var faceNormaly = 0.0; // facet normal y coordinate
  38601. var faceNormalz = 0.0; // facet normal z coordinate
  38602. var length = 0.0; // facet normal length before normalization
  38603. var v1x = 0; // vector1 x index in the positions array
  38604. var v1y = 0; // vector1 y index in the positions array
  38605. var v1z = 0; // vector1 z index in the positions array
  38606. var v2x = 0; // vector2 x index in the positions array
  38607. var v2y = 0; // vector2 y index in the positions array
  38608. var v2z = 0; // vector2 z index in the positions array
  38609. var v3x = 0; // vector3 x index in the positions array
  38610. var v3y = 0; // vector3 y index in the positions array
  38611. var v3z = 0; // vector3 z index in the positions array
  38612. var computeFacetNormals = false;
  38613. var computeFacetPositions = false;
  38614. var computeFacetPartitioning = false;
  38615. var computeDepthSort = false;
  38616. var faceNormalSign = 1;
  38617. var ratio = 0;
  38618. var distanceTo = null;
  38619. if (options) {
  38620. computeFacetNormals = (options.facetNormals) ? true : false;
  38621. computeFacetPositions = (options.facetPositions) ? true : false;
  38622. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38623. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38624. ratio = options.ratio || 0;
  38625. computeDepthSort = (options.depthSort) ? true : false;
  38626. distanceTo = (options.distanceTo);
  38627. if (computeDepthSort) {
  38628. if (distanceTo === undefined) {
  38629. distanceTo = BABYLON.Vector3.Zero();
  38630. }
  38631. var depthSortedFacets = options.depthSortedFacets;
  38632. }
  38633. }
  38634. // facetPartitioning reinit if needed
  38635. var xSubRatio = 0;
  38636. var ySubRatio = 0;
  38637. var zSubRatio = 0;
  38638. var subSq = 0;
  38639. if (computeFacetPartitioning && options && options.bbSize) {
  38640. var ox = 0; // X partitioning index for facet position
  38641. var oy = 0; // Y partinioning index for facet position
  38642. var oz = 0; // Z partinioning index for facet position
  38643. var b1x = 0; // X partitioning index for facet v1 vertex
  38644. var b1y = 0; // Y partitioning index for facet v1 vertex
  38645. var b1z = 0; // z partitioning index for facet v1 vertex
  38646. var b2x = 0; // X partitioning index for facet v2 vertex
  38647. var b2y = 0; // Y partitioning index for facet v2 vertex
  38648. var b2z = 0; // Z partitioning index for facet v2 vertex
  38649. var b3x = 0; // X partitioning index for facet v3 vertex
  38650. var b3y = 0; // Y partitioning index for facet v3 vertex
  38651. var b3z = 0; // Z partitioning index for facet v3 vertex
  38652. var block_idx_o = 0; // facet barycenter block index
  38653. var block_idx_v1 = 0; // v1 vertex block index
  38654. var block_idx_v2 = 0; // v2 vertex block index
  38655. var block_idx_v3 = 0; // v3 vertex block index
  38656. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38657. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38658. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38659. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38660. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38661. subSq = options.subDiv.max * options.subDiv.max;
  38662. options.facetPartitioning.length = 0;
  38663. }
  38664. // reset the normals
  38665. for (index = 0; index < positions.length; index++) {
  38666. normals[index] = 0.0;
  38667. }
  38668. // Loop : 1 indice triplet = 1 facet
  38669. var nbFaces = (indices.length / 3) | 0;
  38670. for (index = 0; index < nbFaces; index++) {
  38671. // get the indexes of the coordinates of each vertex of the facet
  38672. v1x = indices[index * 3] * 3;
  38673. v1y = v1x + 1;
  38674. v1z = v1x + 2;
  38675. v2x = indices[index * 3 + 1] * 3;
  38676. v2y = v2x + 1;
  38677. v2z = v2x + 2;
  38678. v3x = indices[index * 3 + 2] * 3;
  38679. v3y = v3x + 1;
  38680. v3z = v3x + 2;
  38681. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38682. p1p2y = positions[v1y] - positions[v2y];
  38683. p1p2z = positions[v1z] - positions[v2z];
  38684. p3p2x = positions[v3x] - positions[v2x];
  38685. p3p2y = positions[v3y] - positions[v2y];
  38686. p3p2z = positions[v3z] - positions[v2z];
  38687. // compute the face normal with the cross product
  38688. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38689. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38690. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38691. // normalize this normal and store it in the array facetData
  38692. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38693. length = (length === 0) ? 1.0 : length;
  38694. faceNormalx /= length;
  38695. faceNormaly /= length;
  38696. faceNormalz /= length;
  38697. if (computeFacetNormals && options) {
  38698. options.facetNormals[index].x = faceNormalx;
  38699. options.facetNormals[index].y = faceNormaly;
  38700. options.facetNormals[index].z = faceNormalz;
  38701. }
  38702. if (computeFacetPositions && options) {
  38703. // compute and the facet barycenter coordinates in the array facetPositions
  38704. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38705. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38706. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38707. }
  38708. if (computeFacetPartitioning && options) {
  38709. // store the facet indexes in arrays in the main facetPartitioning array :
  38710. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38711. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38712. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38713. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38714. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38715. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38716. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38717. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38718. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38719. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38720. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38721. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38722. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38723. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38724. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38725. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38726. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38727. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38728. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38729. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38730. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38731. // push each facet index in each block containing the vertex
  38732. options.facetPartitioning[block_idx_v1].push(index);
  38733. if (block_idx_v2 != block_idx_v1) {
  38734. options.facetPartitioning[block_idx_v2].push(index);
  38735. }
  38736. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38737. options.facetPartitioning[block_idx_v3].push(index);
  38738. }
  38739. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38740. options.facetPartitioning[block_idx_o].push(index);
  38741. }
  38742. }
  38743. if (computeDepthSort && options && options.facetPositions) {
  38744. var dsf = depthSortedFacets[index];
  38745. dsf.ind = index * 3;
  38746. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38747. }
  38748. // compute the normals anyway
  38749. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38750. normals[v1y] += faceNormaly;
  38751. normals[v1z] += faceNormalz;
  38752. normals[v2x] += faceNormalx;
  38753. normals[v2y] += faceNormaly;
  38754. normals[v2z] += faceNormalz;
  38755. normals[v3x] += faceNormalx;
  38756. normals[v3y] += faceNormaly;
  38757. normals[v3z] += faceNormalz;
  38758. }
  38759. // last normalization of each normal
  38760. for (index = 0; index < normals.length / 3; index++) {
  38761. faceNormalx = normals[index * 3];
  38762. faceNormaly = normals[index * 3 + 1];
  38763. faceNormalz = normals[index * 3 + 2];
  38764. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38765. length = (length === 0) ? 1.0 : length;
  38766. faceNormalx /= length;
  38767. faceNormaly /= length;
  38768. faceNormalz /= length;
  38769. normals[index * 3] = faceNormalx;
  38770. normals[index * 3 + 1] = faceNormaly;
  38771. normals[index * 3 + 2] = faceNormalz;
  38772. }
  38773. };
  38774. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38775. var li = indices.length;
  38776. var ln = normals.length;
  38777. var i;
  38778. var n;
  38779. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38780. switch (sideOrientation) {
  38781. case BABYLON.Mesh.FRONTSIDE:
  38782. // nothing changed
  38783. break;
  38784. case BABYLON.Mesh.BACKSIDE:
  38785. var tmp;
  38786. // indices
  38787. for (i = 0; i < li; i += 3) {
  38788. tmp = indices[i];
  38789. indices[i] = indices[i + 2];
  38790. indices[i + 2] = tmp;
  38791. }
  38792. // normals
  38793. for (n = 0; n < ln; n++) {
  38794. normals[n] = -normals[n];
  38795. }
  38796. break;
  38797. case BABYLON.Mesh.DOUBLESIDE:
  38798. // positions
  38799. var lp = positions.length;
  38800. var l = lp / 3;
  38801. for (var p = 0; p < lp; p++) {
  38802. positions[lp + p] = positions[p];
  38803. }
  38804. // indices
  38805. for (i = 0; i < li; i += 3) {
  38806. indices[i + li] = indices[i + 2] + l;
  38807. indices[i + 1 + li] = indices[i + 1] + l;
  38808. indices[i + 2 + li] = indices[i] + l;
  38809. }
  38810. // normals
  38811. for (n = 0; n < ln; n++) {
  38812. normals[ln + n] = -normals[n];
  38813. }
  38814. // uvs
  38815. var lu = uvs.length;
  38816. var u = 0;
  38817. for (u = 0; u < lu; u++) {
  38818. uvs[u + lu] = uvs[u];
  38819. }
  38820. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38821. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38822. u = 0;
  38823. for (i = 0; i < lu / 2; i++) {
  38824. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38825. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38826. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38827. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38828. u += 2;
  38829. }
  38830. break;
  38831. }
  38832. };
  38833. /**
  38834. * Applies VertexData created from the imported parameters to the geometry
  38835. * @param parsedVertexData the parsed data from an imported file
  38836. * @param geometry the geometry to apply the VertexData to
  38837. */
  38838. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38839. var vertexData = new VertexData();
  38840. // positions
  38841. var positions = parsedVertexData.positions;
  38842. if (positions) {
  38843. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38844. }
  38845. // normals
  38846. var normals = parsedVertexData.normals;
  38847. if (normals) {
  38848. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38849. }
  38850. // tangents
  38851. var tangents = parsedVertexData.tangents;
  38852. if (tangents) {
  38853. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38854. }
  38855. // uvs
  38856. var uvs = parsedVertexData.uvs;
  38857. if (uvs) {
  38858. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38859. }
  38860. // uv2s
  38861. var uv2s = parsedVertexData.uv2s;
  38862. if (uv2s) {
  38863. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38864. }
  38865. // uv3s
  38866. var uv3s = parsedVertexData.uv3s;
  38867. if (uv3s) {
  38868. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38869. }
  38870. // uv4s
  38871. var uv4s = parsedVertexData.uv4s;
  38872. if (uv4s) {
  38873. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38874. }
  38875. // uv5s
  38876. var uv5s = parsedVertexData.uv5s;
  38877. if (uv5s) {
  38878. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38879. }
  38880. // uv6s
  38881. var uv6s = parsedVertexData.uv6s;
  38882. if (uv6s) {
  38883. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38884. }
  38885. // colors
  38886. var colors = parsedVertexData.colors;
  38887. if (colors) {
  38888. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38889. }
  38890. // matricesIndices
  38891. var matricesIndices = parsedVertexData.matricesIndices;
  38892. if (matricesIndices) {
  38893. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38894. }
  38895. // matricesWeights
  38896. var matricesWeights = parsedVertexData.matricesWeights;
  38897. if (matricesWeights) {
  38898. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38899. }
  38900. // indices
  38901. var indices = parsedVertexData.indices;
  38902. if (indices) {
  38903. vertexData.indices = indices;
  38904. }
  38905. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38906. };
  38907. return VertexData;
  38908. }());
  38909. BABYLON.VertexData = VertexData;
  38910. })(BABYLON || (BABYLON = {}));
  38911. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38912. var BABYLON;
  38913. (function (BABYLON) {
  38914. /**
  38915. * Class used to store geometry data (vertex buffers + index buffer)
  38916. */
  38917. var Geometry = /** @class */ (function () {
  38918. /**
  38919. * Creates a new geometry
  38920. * @param id defines the unique ID
  38921. * @param scene defines the hosting scene
  38922. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38923. * @param updatable defines if geometry must be updatable (false by default)
  38924. * @param mesh defines the mesh that will be associated with the geometry
  38925. */
  38926. function Geometry(id, scene, vertexData, updatable, mesh) {
  38927. if (updatable === void 0) { updatable = false; }
  38928. if (mesh === void 0) { mesh = null; }
  38929. /**
  38930. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38931. */
  38932. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38933. this._totalVertices = 0;
  38934. this._isDisposed = false;
  38935. this._indexBufferIsUpdatable = false;
  38936. this.id = id;
  38937. this._engine = scene.getEngine();
  38938. this._meshes = [];
  38939. this._scene = scene;
  38940. //Init vertex buffer cache
  38941. this._vertexBuffers = {};
  38942. this._indices = [];
  38943. this._updatable = updatable;
  38944. // vertexData
  38945. if (vertexData) {
  38946. this.setAllVerticesData(vertexData, updatable);
  38947. }
  38948. else {
  38949. this._totalVertices = 0;
  38950. this._indices = [];
  38951. }
  38952. if (this._engine.getCaps().vertexArrayObject) {
  38953. this._vertexArrayObjects = {};
  38954. }
  38955. // applyToMesh
  38956. if (mesh) {
  38957. if (mesh.getClassName() === "LinesMesh") {
  38958. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38959. this._updateExtend();
  38960. }
  38961. this.applyToMesh(mesh);
  38962. mesh.computeWorldMatrix(true);
  38963. }
  38964. }
  38965. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38966. /**
  38967. * 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
  38968. */
  38969. get: function () {
  38970. return this._boundingBias;
  38971. },
  38972. /**
  38973. * 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
  38974. */
  38975. set: function (value) {
  38976. if (this._boundingBias && this._boundingBias.equals(value)) {
  38977. return;
  38978. }
  38979. this._boundingBias = value.clone();
  38980. this._updateBoundingInfo(true, null);
  38981. },
  38982. enumerable: true,
  38983. configurable: true
  38984. });
  38985. /**
  38986. * Static function used to attach a new empty geometry to a mesh
  38987. * @param mesh defines the mesh to attach the geometry to
  38988. * @returns the new {BABYLON.Geometry}
  38989. */
  38990. Geometry.CreateGeometryForMesh = function (mesh) {
  38991. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38992. geometry.applyToMesh(mesh);
  38993. return geometry;
  38994. };
  38995. Object.defineProperty(Geometry.prototype, "extend", {
  38996. /**
  38997. * Gets the current extend of the geometry
  38998. */
  38999. get: function () {
  39000. return this._extend;
  39001. },
  39002. enumerable: true,
  39003. configurable: true
  39004. });
  39005. /**
  39006. * Gets the hosting scene
  39007. * @returns the hosting {BABYLON.Scene}
  39008. */
  39009. Geometry.prototype.getScene = function () {
  39010. return this._scene;
  39011. };
  39012. /**
  39013. * Gets the hosting engine
  39014. * @returns the hosting {BABYLON.Engine}
  39015. */
  39016. Geometry.prototype.getEngine = function () {
  39017. return this._engine;
  39018. };
  39019. /**
  39020. * Defines if the geometry is ready to use
  39021. * @returns true if the geometry is ready to be used
  39022. */
  39023. Geometry.prototype.isReady = function () {
  39024. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39025. };
  39026. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39027. /**
  39028. * Gets a value indicating that the geometry should not be serialized
  39029. */
  39030. get: function () {
  39031. for (var index = 0; index < this._meshes.length; index++) {
  39032. if (!this._meshes[index].doNotSerialize) {
  39033. return false;
  39034. }
  39035. }
  39036. return true;
  39037. },
  39038. enumerable: true,
  39039. configurable: true
  39040. });
  39041. /** @hidden */
  39042. Geometry.prototype._rebuild = function () {
  39043. if (this._vertexArrayObjects) {
  39044. this._vertexArrayObjects = {};
  39045. }
  39046. // Index buffer
  39047. if (this._meshes.length !== 0 && this._indices) {
  39048. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39049. }
  39050. // Vertex buffers
  39051. for (var key in this._vertexBuffers) {
  39052. var vertexBuffer = this._vertexBuffers[key];
  39053. vertexBuffer._rebuild();
  39054. }
  39055. };
  39056. /**
  39057. * Affects all geometry data in one call
  39058. * @param vertexData defines the geometry data
  39059. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39060. */
  39061. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39062. vertexData.applyToGeometry(this, updatable);
  39063. this.notifyUpdate();
  39064. };
  39065. /**
  39066. * Set specific vertex data
  39067. * @param kind defines the data kind (Position, normal, etc...)
  39068. * @param data defines the vertex data to use
  39069. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39070. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39071. */
  39072. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39073. if (updatable === void 0) { updatable = false; }
  39074. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39075. this.setVerticesBuffer(buffer);
  39076. };
  39077. /**
  39078. * Removes a specific vertex data
  39079. * @param kind defines the data kind (Position, normal, etc...)
  39080. */
  39081. Geometry.prototype.removeVerticesData = function (kind) {
  39082. if (this._vertexBuffers[kind]) {
  39083. this._vertexBuffers[kind].dispose();
  39084. delete this._vertexBuffers[kind];
  39085. }
  39086. };
  39087. /**
  39088. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39089. * @param buffer defines the vertex buffer to use
  39090. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39091. */
  39092. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39093. if (totalVertices === void 0) { totalVertices = null; }
  39094. var kind = buffer.getKind();
  39095. if (this._vertexBuffers[kind]) {
  39096. this._vertexBuffers[kind].dispose();
  39097. }
  39098. this._vertexBuffers[kind] = buffer;
  39099. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39100. var data = buffer.getData();
  39101. if (totalVertices != null) {
  39102. this._totalVertices = totalVertices;
  39103. }
  39104. else {
  39105. if (data != null) {
  39106. this._totalVertices = data.length / (buffer.byteStride / 4);
  39107. }
  39108. }
  39109. this._updateExtend(data);
  39110. this._resetPointsArrayCache();
  39111. var meshes = this._meshes;
  39112. var numOfMeshes = meshes.length;
  39113. for (var index = 0; index < numOfMeshes; index++) {
  39114. var mesh = meshes[index];
  39115. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39116. mesh._createGlobalSubMesh(false);
  39117. mesh.computeWorldMatrix(true);
  39118. }
  39119. }
  39120. this.notifyUpdate(kind);
  39121. if (this._vertexArrayObjects) {
  39122. this._disposeVertexArrayObjects();
  39123. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39124. }
  39125. };
  39126. /**
  39127. * Update a specific vertex buffer
  39128. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39129. * It will do nothing if the buffer is not updatable
  39130. * @param kind defines the data kind (Position, normal, etc...)
  39131. * @param data defines the data to use
  39132. * @param offset defines the offset in the target buffer where to store the data
  39133. * @param useBytes set to true if the offset is in bytes
  39134. */
  39135. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39136. if (useBytes === void 0) { useBytes = false; }
  39137. var vertexBuffer = this.getVertexBuffer(kind);
  39138. if (!vertexBuffer) {
  39139. return;
  39140. }
  39141. vertexBuffer.updateDirectly(data, offset, useBytes);
  39142. this.notifyUpdate(kind);
  39143. };
  39144. /**
  39145. * Update a specific vertex buffer
  39146. * This function will create a new buffer if the current one is not updatable
  39147. * @param kind defines the data kind (Position, normal, etc...)
  39148. * @param data defines the data to use
  39149. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39150. */
  39151. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39152. if (updateExtends === void 0) { updateExtends = false; }
  39153. var vertexBuffer = this.getVertexBuffer(kind);
  39154. if (!vertexBuffer) {
  39155. return;
  39156. }
  39157. vertexBuffer.update(data);
  39158. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39159. this._updateBoundingInfo(updateExtends, data);
  39160. }
  39161. this.notifyUpdate(kind);
  39162. };
  39163. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39164. if (updateExtends) {
  39165. this._updateExtend(data);
  39166. }
  39167. var meshes = this._meshes;
  39168. var numOfMeshes = meshes.length;
  39169. this._resetPointsArrayCache();
  39170. for (var index = 0; index < numOfMeshes; index++) {
  39171. var mesh = meshes[index];
  39172. if (updateExtends) {
  39173. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39174. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39175. var subMesh = mesh.subMeshes[subIndex];
  39176. subMesh.refreshBoundingInfo();
  39177. }
  39178. }
  39179. }
  39180. };
  39181. /** @hidden */
  39182. Geometry.prototype._bind = function (effect, indexToBind) {
  39183. if (!effect) {
  39184. return;
  39185. }
  39186. if (indexToBind === undefined) {
  39187. indexToBind = this._indexBuffer;
  39188. }
  39189. var vbs = this.getVertexBuffers();
  39190. if (!vbs) {
  39191. return;
  39192. }
  39193. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39194. this._engine.bindBuffers(vbs, indexToBind, effect);
  39195. return;
  39196. }
  39197. // Using VAO
  39198. if (!this._vertexArrayObjects[effect.key]) {
  39199. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39200. }
  39201. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39202. };
  39203. /**
  39204. * Gets total number of vertices
  39205. * @returns the total number of vertices
  39206. */
  39207. Geometry.prototype.getTotalVertices = function () {
  39208. if (!this.isReady()) {
  39209. return 0;
  39210. }
  39211. return this._totalVertices;
  39212. };
  39213. /**
  39214. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39215. * @param kind defines the data kind (Position, normal, etc...)
  39216. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39217. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39218. * @returns a float array containing vertex data
  39219. */
  39220. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39221. var vertexBuffer = this.getVertexBuffer(kind);
  39222. if (!vertexBuffer) {
  39223. return null;
  39224. }
  39225. var data = vertexBuffer.getData();
  39226. if (!data) {
  39227. return null;
  39228. }
  39229. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39230. var count = this._totalVertices * vertexBuffer.getSize();
  39231. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39232. var copy_1 = new Array(count);
  39233. vertexBuffer.forEach(count, function (value, index) {
  39234. copy_1[index] = value;
  39235. });
  39236. return copy_1;
  39237. }
  39238. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39239. if (data instanceof Array) {
  39240. var offset = vertexBuffer.byteOffset / 4;
  39241. return BABYLON.Tools.Slice(data, offset, offset + count);
  39242. }
  39243. else if (data instanceof ArrayBuffer) {
  39244. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39245. }
  39246. else {
  39247. var offset = data.byteOffset + vertexBuffer.byteOffset;
  39248. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39249. var result = new Float32Array(count);
  39250. var source = new Float32Array(data.buffer, offset, count);
  39251. result.set(source);
  39252. return result;
  39253. }
  39254. return new Float32Array(data.buffer, offset, count);
  39255. }
  39256. }
  39257. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39258. return BABYLON.Tools.Slice(data);
  39259. }
  39260. return data;
  39261. };
  39262. /**
  39263. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39264. * @param kind defines the data kind (Position, normal, etc...)
  39265. * @returns true if the vertex buffer with the specified kind is updatable
  39266. */
  39267. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39268. var vb = this._vertexBuffers[kind];
  39269. if (!vb) {
  39270. return false;
  39271. }
  39272. return vb.isUpdatable();
  39273. };
  39274. /**
  39275. * Gets a specific vertex buffer
  39276. * @param kind defines the data kind (Position, normal, etc...)
  39277. * @returns a {BABYLON.VertexBuffer}
  39278. */
  39279. Geometry.prototype.getVertexBuffer = function (kind) {
  39280. if (!this.isReady()) {
  39281. return null;
  39282. }
  39283. return this._vertexBuffers[kind];
  39284. };
  39285. /**
  39286. * Returns all vertex buffers
  39287. * @return an object holding all vertex buffers indexed by kind
  39288. */
  39289. Geometry.prototype.getVertexBuffers = function () {
  39290. if (!this.isReady()) {
  39291. return null;
  39292. }
  39293. return this._vertexBuffers;
  39294. };
  39295. /**
  39296. * Gets a boolean indicating if specific vertex buffer is present
  39297. * @param kind defines the data kind (Position, normal, etc...)
  39298. * @returns true if data is present
  39299. */
  39300. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39301. if (!this._vertexBuffers) {
  39302. if (this._delayInfo) {
  39303. return this._delayInfo.indexOf(kind) !== -1;
  39304. }
  39305. return false;
  39306. }
  39307. return this._vertexBuffers[kind] !== undefined;
  39308. };
  39309. /**
  39310. * Gets a list of all attached data kinds (Position, normal, etc...)
  39311. * @returns a list of string containing all kinds
  39312. */
  39313. Geometry.prototype.getVerticesDataKinds = function () {
  39314. var result = [];
  39315. var kind;
  39316. if (!this._vertexBuffers && this._delayInfo) {
  39317. for (kind in this._delayInfo) {
  39318. result.push(kind);
  39319. }
  39320. }
  39321. else {
  39322. for (kind in this._vertexBuffers) {
  39323. result.push(kind);
  39324. }
  39325. }
  39326. return result;
  39327. };
  39328. /**
  39329. * Update index buffer
  39330. * @param indices defines the indices to store in the index buffer
  39331. * @param offset defines the offset in the target buffer where to store the data
  39332. */
  39333. Geometry.prototype.updateIndices = function (indices, offset) {
  39334. if (!this._indexBuffer) {
  39335. return;
  39336. }
  39337. if (!this._indexBufferIsUpdatable) {
  39338. this.setIndices(indices, null, true);
  39339. }
  39340. else {
  39341. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39342. }
  39343. };
  39344. /**
  39345. * Creates a new index buffer
  39346. * @param indices defines the indices to store in the index buffer
  39347. * @param totalVertices defines the total number of vertices (could be null)
  39348. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39349. */
  39350. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39351. if (totalVertices === void 0) { totalVertices = null; }
  39352. if (updatable === void 0) { updatable = false; }
  39353. if (this._indexBuffer) {
  39354. this._engine._releaseBuffer(this._indexBuffer);
  39355. }
  39356. this._disposeVertexArrayObjects();
  39357. this._indices = indices;
  39358. this._indexBufferIsUpdatable = updatable;
  39359. if (this._meshes.length !== 0 && this._indices) {
  39360. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39361. }
  39362. if (totalVertices != undefined) { // including null and undefined
  39363. this._totalVertices = totalVertices;
  39364. }
  39365. var meshes = this._meshes;
  39366. var numOfMeshes = meshes.length;
  39367. for (var index = 0; index < numOfMeshes; index++) {
  39368. meshes[index]._createGlobalSubMesh(true);
  39369. }
  39370. this.notifyUpdate();
  39371. };
  39372. /**
  39373. * Return the total number of indices
  39374. * @returns the total number of indices
  39375. */
  39376. Geometry.prototype.getTotalIndices = function () {
  39377. if (!this.isReady()) {
  39378. return 0;
  39379. }
  39380. return this._indices.length;
  39381. };
  39382. /**
  39383. * Gets the index buffer array
  39384. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39385. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39386. * @returns the index buffer array
  39387. */
  39388. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  39389. if (!this.isReady()) {
  39390. return null;
  39391. }
  39392. var orig = this._indices;
  39393. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  39394. return orig;
  39395. }
  39396. else {
  39397. var len = orig.length;
  39398. var copy = [];
  39399. for (var i = 0; i < len; i++) {
  39400. copy.push(orig[i]);
  39401. }
  39402. return copy;
  39403. }
  39404. };
  39405. /**
  39406. * Gets the index buffer
  39407. * @return the index buffer
  39408. */
  39409. Geometry.prototype.getIndexBuffer = function () {
  39410. if (!this.isReady()) {
  39411. return null;
  39412. }
  39413. return this._indexBuffer;
  39414. };
  39415. /** @hidden */
  39416. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39417. if (effect === void 0) { effect = null; }
  39418. if (!effect || !this._vertexArrayObjects) {
  39419. return;
  39420. }
  39421. if (this._vertexArrayObjects[effect.key]) {
  39422. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39423. delete this._vertexArrayObjects[effect.key];
  39424. }
  39425. };
  39426. /**
  39427. * Release the associated resources for a specific mesh
  39428. * @param mesh defines the source mesh
  39429. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39430. */
  39431. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39432. var meshes = this._meshes;
  39433. var index = meshes.indexOf(mesh);
  39434. if (index === -1) {
  39435. return;
  39436. }
  39437. meshes.splice(index, 1);
  39438. mesh._geometry = null;
  39439. if (meshes.length === 0 && shouldDispose) {
  39440. this.dispose();
  39441. }
  39442. };
  39443. /**
  39444. * Apply current geometry to a given mesh
  39445. * @param mesh defines the mesh to apply geometry to
  39446. */
  39447. Geometry.prototype.applyToMesh = function (mesh) {
  39448. if (mesh._geometry === this) {
  39449. return;
  39450. }
  39451. var previousGeometry = mesh._geometry;
  39452. if (previousGeometry) {
  39453. previousGeometry.releaseForMesh(mesh);
  39454. }
  39455. var meshes = this._meshes;
  39456. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39457. mesh._geometry = this;
  39458. this._scene.pushGeometry(this);
  39459. meshes.push(mesh);
  39460. if (this.isReady()) {
  39461. this._applyToMesh(mesh);
  39462. }
  39463. else {
  39464. mesh._boundingInfo = this._boundingInfo;
  39465. }
  39466. };
  39467. Geometry.prototype._updateExtend = function (data) {
  39468. if (data === void 0) { data = null; }
  39469. if (!data) {
  39470. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39471. }
  39472. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39473. };
  39474. Geometry.prototype._applyToMesh = function (mesh) {
  39475. var numOfMeshes = this._meshes.length;
  39476. // vertexBuffers
  39477. for (var kind in this._vertexBuffers) {
  39478. if (numOfMeshes === 1) {
  39479. this._vertexBuffers[kind].create();
  39480. }
  39481. var buffer = this._vertexBuffers[kind].getBuffer();
  39482. if (buffer)
  39483. buffer.references = numOfMeshes;
  39484. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39485. if (!this._extend) {
  39486. this._updateExtend();
  39487. }
  39488. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39489. mesh._createGlobalSubMesh(false);
  39490. //bounding info was just created again, world matrix should be applied again.
  39491. mesh._updateBoundingInfo();
  39492. }
  39493. }
  39494. // indexBuffer
  39495. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39496. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39497. }
  39498. if (this._indexBuffer) {
  39499. this._indexBuffer.references = numOfMeshes;
  39500. }
  39501. };
  39502. Geometry.prototype.notifyUpdate = function (kind) {
  39503. if (this.onGeometryUpdated) {
  39504. this.onGeometryUpdated(this, kind);
  39505. }
  39506. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39507. var mesh = _a[_i];
  39508. mesh._markSubMeshesAsAttributesDirty();
  39509. }
  39510. };
  39511. /**
  39512. * Load the geometry if it was flagged as delay loaded
  39513. * @param scene defines the hosting scene
  39514. * @param onLoaded defines a callback called when the geometry is loaded
  39515. */
  39516. Geometry.prototype.load = function (scene, onLoaded) {
  39517. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39518. return;
  39519. }
  39520. if (this.isReady()) {
  39521. if (onLoaded) {
  39522. onLoaded();
  39523. }
  39524. return;
  39525. }
  39526. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39527. this._queueLoad(scene, onLoaded);
  39528. };
  39529. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39530. var _this = this;
  39531. if (!this.delayLoadingFile) {
  39532. return;
  39533. }
  39534. scene._addPendingData(this);
  39535. scene._loadFile(this.delayLoadingFile, function (data) {
  39536. if (!_this._delayLoadingFunction) {
  39537. return;
  39538. }
  39539. _this._delayLoadingFunction(JSON.parse(data), _this);
  39540. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39541. _this._delayInfo = [];
  39542. scene._removePendingData(_this);
  39543. var meshes = _this._meshes;
  39544. var numOfMeshes = meshes.length;
  39545. for (var index = 0; index < numOfMeshes; index++) {
  39546. _this._applyToMesh(meshes[index]);
  39547. }
  39548. if (onLoaded) {
  39549. onLoaded();
  39550. }
  39551. }, undefined, true);
  39552. };
  39553. /**
  39554. * Invert the geometry to move from a right handed system to a left handed one.
  39555. */
  39556. Geometry.prototype.toLeftHanded = function () {
  39557. // Flip faces
  39558. var tIndices = this.getIndices(false);
  39559. if (tIndices != null && tIndices.length > 0) {
  39560. for (var i = 0; i < tIndices.length; i += 3) {
  39561. var tTemp = tIndices[i + 0];
  39562. tIndices[i + 0] = tIndices[i + 2];
  39563. tIndices[i + 2] = tTemp;
  39564. }
  39565. this.setIndices(tIndices);
  39566. }
  39567. // Negate position.z
  39568. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39569. if (tPositions != null && tPositions.length > 0) {
  39570. for (var i = 0; i < tPositions.length; i += 3) {
  39571. tPositions[i + 2] = -tPositions[i + 2];
  39572. }
  39573. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39574. }
  39575. // Negate normal.z
  39576. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39577. if (tNormals != null && tNormals.length > 0) {
  39578. for (var i = 0; i < tNormals.length; i += 3) {
  39579. tNormals[i + 2] = -tNormals[i + 2];
  39580. }
  39581. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39582. }
  39583. };
  39584. // Cache
  39585. /** @hidden */
  39586. Geometry.prototype._resetPointsArrayCache = function () {
  39587. this._positions = null;
  39588. };
  39589. /** @hidden */
  39590. Geometry.prototype._generatePointsArray = function () {
  39591. if (this._positions)
  39592. return true;
  39593. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39594. if (!data || data.length === 0) {
  39595. return false;
  39596. }
  39597. this._positions = [];
  39598. for (var index = 0; index < data.length; index += 3) {
  39599. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39600. }
  39601. return true;
  39602. };
  39603. /**
  39604. * Gets a value indicating if the geometry is disposed
  39605. * @returns true if the geometry was disposed
  39606. */
  39607. Geometry.prototype.isDisposed = function () {
  39608. return this._isDisposed;
  39609. };
  39610. Geometry.prototype._disposeVertexArrayObjects = function () {
  39611. if (this._vertexArrayObjects) {
  39612. for (var kind in this._vertexArrayObjects) {
  39613. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39614. }
  39615. this._vertexArrayObjects = {};
  39616. }
  39617. };
  39618. /**
  39619. * Free all associated resources
  39620. */
  39621. Geometry.prototype.dispose = function () {
  39622. var meshes = this._meshes;
  39623. var numOfMeshes = meshes.length;
  39624. var index;
  39625. for (index = 0; index < numOfMeshes; index++) {
  39626. this.releaseForMesh(meshes[index]);
  39627. }
  39628. this._meshes = [];
  39629. this._disposeVertexArrayObjects();
  39630. for (var kind in this._vertexBuffers) {
  39631. this._vertexBuffers[kind].dispose();
  39632. }
  39633. this._vertexBuffers = {};
  39634. this._totalVertices = 0;
  39635. if (this._indexBuffer) {
  39636. this._engine._releaseBuffer(this._indexBuffer);
  39637. }
  39638. this._indexBuffer = null;
  39639. this._indices = [];
  39640. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39641. this.delayLoadingFile = null;
  39642. this._delayLoadingFunction = null;
  39643. this._delayInfo = [];
  39644. this._boundingInfo = null;
  39645. this._scene.removeGeometry(this);
  39646. this._isDisposed = true;
  39647. };
  39648. /**
  39649. * Clone the current geometry into a new geometry
  39650. * @param id defines the unique ID of the new geometry
  39651. * @returns a new geometry object
  39652. */
  39653. Geometry.prototype.copy = function (id) {
  39654. var vertexData = new BABYLON.VertexData();
  39655. vertexData.indices = [];
  39656. var indices = this.getIndices();
  39657. if (indices) {
  39658. for (var index = 0; index < indices.length; index++) {
  39659. vertexData.indices.push(indices[index]);
  39660. }
  39661. }
  39662. var updatable = false;
  39663. var stopChecking = false;
  39664. var kind;
  39665. for (kind in this._vertexBuffers) {
  39666. // using slice() to make a copy of the array and not just reference it
  39667. var data = this.getVerticesData(kind);
  39668. if (data instanceof Float32Array) {
  39669. vertexData.set(new Float32Array(data), kind);
  39670. }
  39671. else {
  39672. vertexData.set(data.slice(0), kind);
  39673. }
  39674. if (!stopChecking) {
  39675. var vb = this.getVertexBuffer(kind);
  39676. if (vb) {
  39677. updatable = vb.isUpdatable();
  39678. stopChecking = !updatable;
  39679. }
  39680. }
  39681. }
  39682. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39683. geometry.delayLoadState = this.delayLoadState;
  39684. geometry.delayLoadingFile = this.delayLoadingFile;
  39685. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39686. for (kind in this._delayInfo) {
  39687. geometry._delayInfo = geometry._delayInfo || [];
  39688. geometry._delayInfo.push(kind);
  39689. }
  39690. // Bounding info
  39691. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39692. return geometry;
  39693. };
  39694. /**
  39695. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39696. * @return a JSON representation of the current geometry data (without the vertices data)
  39697. */
  39698. Geometry.prototype.serialize = function () {
  39699. var serializationObject = {};
  39700. serializationObject.id = this.id;
  39701. serializationObject.updatable = this._updatable;
  39702. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39703. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39704. }
  39705. return serializationObject;
  39706. };
  39707. Geometry.prototype.toNumberArray = function (origin) {
  39708. if (Array.isArray(origin)) {
  39709. return origin;
  39710. }
  39711. else {
  39712. return Array.prototype.slice.call(origin);
  39713. }
  39714. };
  39715. /**
  39716. * Serialize all vertices data into a JSON oject
  39717. * @returns a JSON representation of the current geometry data
  39718. */
  39719. Geometry.prototype.serializeVerticeData = function () {
  39720. var serializationObject = this.serialize();
  39721. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39722. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39723. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39724. serializationObject.positions._updatable = true;
  39725. }
  39726. }
  39727. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39728. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39729. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39730. serializationObject.normals._updatable = true;
  39731. }
  39732. }
  39733. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39734. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39735. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39736. serializationObject.tangets._updatable = true;
  39737. }
  39738. }
  39739. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39740. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39741. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39742. serializationObject.uvs._updatable = true;
  39743. }
  39744. }
  39745. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39746. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39747. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39748. serializationObject.uv2s._updatable = true;
  39749. }
  39750. }
  39751. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39752. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39753. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39754. serializationObject.uv3s._updatable = true;
  39755. }
  39756. }
  39757. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39758. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39759. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39760. serializationObject.uv4s._updatable = true;
  39761. }
  39762. }
  39763. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39764. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39765. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39766. serializationObject.uv5s._updatable = true;
  39767. }
  39768. }
  39769. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39770. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39771. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39772. serializationObject.uv6s._updatable = true;
  39773. }
  39774. }
  39775. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39776. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39777. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39778. serializationObject.colors._updatable = true;
  39779. }
  39780. }
  39781. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39782. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39783. serializationObject.matricesIndices._isExpanded = true;
  39784. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39785. serializationObject.matricesIndices._updatable = true;
  39786. }
  39787. }
  39788. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39789. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39790. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39791. serializationObject.matricesWeights._updatable = true;
  39792. }
  39793. }
  39794. serializationObject.indices = this.toNumberArray(this.getIndices());
  39795. return serializationObject;
  39796. };
  39797. // Statics
  39798. /**
  39799. * Extracts a clone of a mesh geometry
  39800. * @param mesh defines the source mesh
  39801. * @param id defines the unique ID of the new geometry object
  39802. * @returns the new geometry object
  39803. */
  39804. Geometry.ExtractFromMesh = function (mesh, id) {
  39805. var geometry = mesh._geometry;
  39806. if (!geometry) {
  39807. return null;
  39808. }
  39809. return geometry.copy(id);
  39810. };
  39811. /**
  39812. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39813. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39814. * Be aware Math.random() could cause collisions, but:
  39815. * "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"
  39816. * @returns a string containing a new GUID
  39817. */
  39818. Geometry.RandomId = function () {
  39819. return BABYLON.Tools.RandomId();
  39820. };
  39821. /** @hidden */
  39822. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39823. var scene = mesh.getScene();
  39824. // Geometry
  39825. var geometryId = parsedGeometry.geometryId;
  39826. if (geometryId) {
  39827. var geometry = scene.getGeometryByID(geometryId);
  39828. if (geometry) {
  39829. geometry.applyToMesh(mesh);
  39830. }
  39831. }
  39832. else if (parsedGeometry instanceof ArrayBuffer) {
  39833. var binaryInfo = mesh._binaryInfo;
  39834. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39835. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39836. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39837. }
  39838. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39839. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39840. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39841. }
  39842. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39843. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39844. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39845. }
  39846. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39847. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39848. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39849. }
  39850. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39851. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39852. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39853. }
  39854. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39855. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39856. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39857. }
  39858. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39859. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39860. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39861. }
  39862. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39863. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39864. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39865. }
  39866. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39867. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39868. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39869. }
  39870. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39871. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39872. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39873. }
  39874. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39875. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39876. var floatIndices = [];
  39877. for (var i = 0; i < matricesIndicesData.length; i++) {
  39878. var index = matricesIndicesData[i];
  39879. floatIndices.push(index & 0x000000FF);
  39880. floatIndices.push((index & 0x0000FF00) >> 8);
  39881. floatIndices.push((index & 0x00FF0000) >> 16);
  39882. floatIndices.push(index >> 24);
  39883. }
  39884. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39885. }
  39886. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39887. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39888. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39889. }
  39890. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39891. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39892. mesh.setIndices(indicesData, null);
  39893. }
  39894. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39895. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39896. mesh.subMeshes = [];
  39897. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39898. var materialIndex = subMeshesData[(i * 5) + 0];
  39899. var verticesStart = subMeshesData[(i * 5) + 1];
  39900. var verticesCount = subMeshesData[(i * 5) + 2];
  39901. var indexStart = subMeshesData[(i * 5) + 3];
  39902. var indexCount = subMeshesData[(i * 5) + 4];
  39903. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39904. }
  39905. }
  39906. }
  39907. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39908. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39909. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39910. if (parsedGeometry.tangents) {
  39911. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39912. }
  39913. if (parsedGeometry.uvs) {
  39914. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39915. }
  39916. if (parsedGeometry.uvs2) {
  39917. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39918. }
  39919. if (parsedGeometry.uvs3) {
  39920. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39921. }
  39922. if (parsedGeometry.uvs4) {
  39923. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39924. }
  39925. if (parsedGeometry.uvs5) {
  39926. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39927. }
  39928. if (parsedGeometry.uvs6) {
  39929. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39930. }
  39931. if (parsedGeometry.colors) {
  39932. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39933. }
  39934. if (parsedGeometry.matricesIndices) {
  39935. if (!parsedGeometry.matricesIndices._isExpanded) {
  39936. var floatIndices = [];
  39937. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39938. var matricesIndex = parsedGeometry.matricesIndices[i];
  39939. floatIndices.push(matricesIndex & 0x000000FF);
  39940. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39941. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39942. floatIndices.push(matricesIndex >> 24);
  39943. }
  39944. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39945. }
  39946. else {
  39947. delete parsedGeometry.matricesIndices._isExpanded;
  39948. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39949. }
  39950. }
  39951. if (parsedGeometry.matricesIndicesExtra) {
  39952. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39953. var floatIndices = [];
  39954. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39955. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39956. floatIndices.push(matricesIndex & 0x000000FF);
  39957. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39958. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39959. floatIndices.push(matricesIndex >> 24);
  39960. }
  39961. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39962. }
  39963. else {
  39964. delete parsedGeometry.matricesIndices._isExpanded;
  39965. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39966. }
  39967. }
  39968. if (parsedGeometry.matricesWeights) {
  39969. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39970. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39971. }
  39972. if (parsedGeometry.matricesWeightsExtra) {
  39973. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39974. }
  39975. mesh.setIndices(parsedGeometry.indices, null);
  39976. }
  39977. // SubMeshes
  39978. if (parsedGeometry.subMeshes) {
  39979. mesh.subMeshes = [];
  39980. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39981. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39982. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39983. }
  39984. }
  39985. // Flat shading
  39986. if (mesh._shouldGenerateFlatShading) {
  39987. mesh.convertToFlatShadedMesh();
  39988. delete mesh._shouldGenerateFlatShading;
  39989. }
  39990. // Update
  39991. mesh.computeWorldMatrix(true);
  39992. // Octree
  39993. var sceneOctree = scene.selectionOctree;
  39994. if (sceneOctree !== undefined && sceneOctree !== null) {
  39995. sceneOctree.addMesh(mesh);
  39996. }
  39997. };
  39998. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39999. var epsilon = 1e-3;
  40000. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40001. return;
  40002. }
  40003. var noInfluenceBoneIndex = 0.0;
  40004. if (parsedGeometry.skeletonId > -1) {
  40005. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40006. if (!skeleton) {
  40007. return;
  40008. }
  40009. noInfluenceBoneIndex = skeleton.bones.length;
  40010. }
  40011. else {
  40012. return;
  40013. }
  40014. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40015. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40016. var matricesWeights = parsedGeometry.matricesWeights;
  40017. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40018. var influencers = parsedGeometry.numBoneInfluencer;
  40019. var size = matricesWeights.length;
  40020. for (var i = 0; i < size; i += 4) {
  40021. var weight = 0.0;
  40022. var firstZeroWeight = -1;
  40023. for (var j = 0; j < 4; j++) {
  40024. var w = matricesWeights[i + j];
  40025. weight += w;
  40026. if (w < epsilon && firstZeroWeight < 0) {
  40027. firstZeroWeight = j;
  40028. }
  40029. }
  40030. if (matricesWeightsExtra) {
  40031. for (var j = 0; j < 4; j++) {
  40032. var w = matricesWeightsExtra[i + j];
  40033. weight += w;
  40034. if (w < epsilon && firstZeroWeight < 0) {
  40035. firstZeroWeight = j + 4;
  40036. }
  40037. }
  40038. }
  40039. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40040. firstZeroWeight = influencers - 1;
  40041. }
  40042. if (weight > epsilon) {
  40043. var mweight = 1.0 / weight;
  40044. for (var j = 0; j < 4; j++) {
  40045. matricesWeights[i + j] *= mweight;
  40046. }
  40047. if (matricesWeightsExtra) {
  40048. for (var j = 0; j < 4; j++) {
  40049. matricesWeightsExtra[i + j] *= mweight;
  40050. }
  40051. }
  40052. }
  40053. else {
  40054. if (firstZeroWeight >= 4) {
  40055. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40056. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40057. }
  40058. else {
  40059. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40060. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40061. }
  40062. }
  40063. }
  40064. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40065. if (parsedGeometry.matricesWeightsExtra) {
  40066. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40067. }
  40068. };
  40069. /**
  40070. * Create a new geometry from persisted data (Using .babylon file format)
  40071. * @param parsedVertexData defines the persisted data
  40072. * @param scene defines the hosting scene
  40073. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40074. * @returns the new geometry object
  40075. */
  40076. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40077. if (scene.getGeometryByID(parsedVertexData.id)) {
  40078. return null; // null since geometry could be something else than a box...
  40079. }
  40080. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40081. if (BABYLON.Tags) {
  40082. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40083. }
  40084. if (parsedVertexData.delayLoadingFile) {
  40085. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40086. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40087. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40088. geometry._delayInfo = [];
  40089. if (parsedVertexData.hasUVs) {
  40090. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40091. }
  40092. if (parsedVertexData.hasUVs2) {
  40093. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40094. }
  40095. if (parsedVertexData.hasUVs3) {
  40096. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40097. }
  40098. if (parsedVertexData.hasUVs4) {
  40099. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40100. }
  40101. if (parsedVertexData.hasUVs5) {
  40102. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40103. }
  40104. if (parsedVertexData.hasUVs6) {
  40105. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40106. }
  40107. if (parsedVertexData.hasColors) {
  40108. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40109. }
  40110. if (parsedVertexData.hasMatricesIndices) {
  40111. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40112. }
  40113. if (parsedVertexData.hasMatricesWeights) {
  40114. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40115. }
  40116. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40117. }
  40118. else {
  40119. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40120. }
  40121. scene.pushGeometry(geometry, true);
  40122. return geometry;
  40123. };
  40124. return Geometry;
  40125. }());
  40126. BABYLON.Geometry = Geometry;
  40127. // Primitives
  40128. /// Abstract class
  40129. /**
  40130. * Abstract class used to provide common services for all typed geometries
  40131. * @hidden
  40132. */
  40133. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40134. __extends(_PrimitiveGeometry, _super);
  40135. /**
  40136. * Creates a new typed geometry
  40137. * @param id defines the unique ID of the geometry
  40138. * @param scene defines the hosting scene
  40139. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40140. * @param mesh defines the hosting mesh (can be null)
  40141. */
  40142. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40143. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40144. if (mesh === void 0) { mesh = null; }
  40145. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40146. _this._canBeRegenerated = _canBeRegenerated;
  40147. _this._beingRegenerated = true;
  40148. _this.regenerate();
  40149. _this._beingRegenerated = false;
  40150. return _this;
  40151. }
  40152. /**
  40153. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40154. * @returns true if the geometry can be regenerated
  40155. */
  40156. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40157. return this._canBeRegenerated;
  40158. };
  40159. /**
  40160. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40161. */
  40162. _PrimitiveGeometry.prototype.regenerate = function () {
  40163. if (!this._canBeRegenerated) {
  40164. return;
  40165. }
  40166. this._beingRegenerated = true;
  40167. this.setAllVerticesData(this._regenerateVertexData(), false);
  40168. this._beingRegenerated = false;
  40169. };
  40170. /**
  40171. * Clone the geometry
  40172. * @param id defines the unique ID of the new geometry
  40173. * @returns the new geometry
  40174. */
  40175. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40176. return _super.prototype.copy.call(this, id);
  40177. };
  40178. // overrides
  40179. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40180. if (!this._beingRegenerated) {
  40181. return;
  40182. }
  40183. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40184. };
  40185. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40186. if (!this._beingRegenerated) {
  40187. return;
  40188. }
  40189. _super.prototype.setVerticesData.call(this, kind, data, false);
  40190. };
  40191. // to override
  40192. /** @hidden */
  40193. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40194. throw new Error("Abstract method");
  40195. };
  40196. _PrimitiveGeometry.prototype.copy = function (id) {
  40197. throw new Error("Must be overriden in sub-classes.");
  40198. };
  40199. _PrimitiveGeometry.prototype.serialize = function () {
  40200. var serializationObject = _super.prototype.serialize.call(this);
  40201. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40202. return serializationObject;
  40203. };
  40204. return _PrimitiveGeometry;
  40205. }(Geometry));
  40206. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40207. /**
  40208. * Creates a ribbon geometry
  40209. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40210. */
  40211. var RibbonGeometry = /** @class */ (function (_super) {
  40212. __extends(RibbonGeometry, _super);
  40213. /**
  40214. * Creates a ribbon geometry
  40215. * @param id defines the unique ID of the geometry
  40216. * @param scene defines the hosting scene
  40217. * @param pathArray defines the array of paths to use
  40218. * @param closeArray defines if the last path and the first path must be joined
  40219. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40220. * @param offset defines the offset between points
  40221. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40222. * @param mesh defines the hosting mesh (can be null)
  40223. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40224. */
  40225. function RibbonGeometry(id, scene,
  40226. /**
  40227. * Defines the array of paths to use
  40228. */
  40229. pathArray,
  40230. /**
  40231. * Defines if the last and first points of each path in your pathArray must be joined
  40232. */
  40233. closeArray,
  40234. /**
  40235. * Defines if the last and first points of each path in your pathArray must be joined
  40236. */
  40237. closePath,
  40238. /**
  40239. * Defines the offset between points
  40240. */
  40241. offset, canBeRegenerated, mesh,
  40242. /**
  40243. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40244. */
  40245. side) {
  40246. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40247. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40248. _this.pathArray = pathArray;
  40249. _this.closeArray = closeArray;
  40250. _this.closePath = closePath;
  40251. _this.offset = offset;
  40252. _this.side = side;
  40253. return _this;
  40254. }
  40255. /** @hidden */
  40256. RibbonGeometry.prototype._regenerateVertexData = function () {
  40257. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40258. };
  40259. RibbonGeometry.prototype.copy = function (id) {
  40260. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40261. };
  40262. return RibbonGeometry;
  40263. }(_PrimitiveGeometry));
  40264. BABYLON.RibbonGeometry = RibbonGeometry;
  40265. /**
  40266. * Creates a box geometry
  40267. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40268. */
  40269. var BoxGeometry = /** @class */ (function (_super) {
  40270. __extends(BoxGeometry, _super);
  40271. /**
  40272. * Creates a box geometry
  40273. * @param id defines the unique ID of the geometry
  40274. * @param scene defines the hosting scene
  40275. * @param size defines the zise of the box (width, height and depth are the same)
  40276. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40277. * @param mesh defines the hosting mesh (can be null)
  40278. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40279. */
  40280. function BoxGeometry(id, scene,
  40281. /**
  40282. * Defines the zise of the box (width, height and depth are the same)
  40283. */
  40284. size, canBeRegenerated, mesh,
  40285. /**
  40286. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40287. */
  40288. side) {
  40289. if (mesh === void 0) { mesh = null; }
  40290. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40291. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40292. _this.size = size;
  40293. _this.side = side;
  40294. return _this;
  40295. }
  40296. /** @hidden */
  40297. BoxGeometry.prototype._regenerateVertexData = function () {
  40298. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40299. };
  40300. BoxGeometry.prototype.copy = function (id) {
  40301. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40302. };
  40303. BoxGeometry.prototype.serialize = function () {
  40304. var serializationObject = _super.prototype.serialize.call(this);
  40305. serializationObject.size = this.size;
  40306. return serializationObject;
  40307. };
  40308. BoxGeometry.Parse = function (parsedBox, scene) {
  40309. if (scene.getGeometryByID(parsedBox.id)) {
  40310. return null; // null since geometry could be something else than a box...
  40311. }
  40312. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40313. if (BABYLON.Tags) {
  40314. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40315. }
  40316. scene.pushGeometry(box, true);
  40317. return box;
  40318. };
  40319. return BoxGeometry;
  40320. }(_PrimitiveGeometry));
  40321. BABYLON.BoxGeometry = BoxGeometry;
  40322. /**
  40323. * Creates a sphere geometry
  40324. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40325. */
  40326. var SphereGeometry = /** @class */ (function (_super) {
  40327. __extends(SphereGeometry, _super);
  40328. /**
  40329. * Create a new sphere geometry
  40330. * @param id defines the unique ID of the geometry
  40331. * @param scene defines the hosting scene
  40332. * @param segments defines the number of segments to use to create the sphere
  40333. * @param diameter defines the diameter of the sphere
  40334. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40335. * @param mesh defines the hosting mesh (can be null)
  40336. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40337. */
  40338. function SphereGeometry(id, scene,
  40339. /**
  40340. * Defines the number of segments to use to create the sphere
  40341. */
  40342. segments,
  40343. /**
  40344. * Defines the diameter of the sphere
  40345. */
  40346. diameter, canBeRegenerated, mesh,
  40347. /**
  40348. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40349. */
  40350. side) {
  40351. if (mesh === void 0) { mesh = null; }
  40352. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40353. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40354. _this.segments = segments;
  40355. _this.diameter = diameter;
  40356. _this.side = side;
  40357. return _this;
  40358. }
  40359. /** @hidden */
  40360. SphereGeometry.prototype._regenerateVertexData = function () {
  40361. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40362. };
  40363. SphereGeometry.prototype.copy = function (id) {
  40364. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40365. };
  40366. SphereGeometry.prototype.serialize = function () {
  40367. var serializationObject = _super.prototype.serialize.call(this);
  40368. serializationObject.segments = this.segments;
  40369. serializationObject.diameter = this.diameter;
  40370. return serializationObject;
  40371. };
  40372. SphereGeometry.Parse = function (parsedSphere, scene) {
  40373. if (scene.getGeometryByID(parsedSphere.id)) {
  40374. return null; // null since geometry could be something else than a sphere...
  40375. }
  40376. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40377. if (BABYLON.Tags) {
  40378. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40379. }
  40380. scene.pushGeometry(sphere, true);
  40381. return sphere;
  40382. };
  40383. return SphereGeometry;
  40384. }(_PrimitiveGeometry));
  40385. BABYLON.SphereGeometry = SphereGeometry;
  40386. /**
  40387. * Creates a disc geometry
  40388. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40389. */
  40390. var DiscGeometry = /** @class */ (function (_super) {
  40391. __extends(DiscGeometry, _super);
  40392. /**
  40393. * Creates a new disc geometry
  40394. * @param id defines the unique ID of the geometry
  40395. * @param scene defines the hosting scene
  40396. * @param radius defines the radius of the disc
  40397. * @param tessellation defines the tesselation factor to apply to the disc
  40398. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40399. * @param mesh defines the hosting mesh (can be null)
  40400. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40401. */
  40402. function DiscGeometry(id, scene,
  40403. /**
  40404. * Defines the radius of the disc
  40405. */
  40406. radius,
  40407. /**
  40408. * Defines the tesselation factor to apply to the disc
  40409. */
  40410. tessellation, canBeRegenerated, mesh,
  40411. /**
  40412. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40413. */
  40414. side) {
  40415. if (mesh === void 0) { mesh = null; }
  40416. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40417. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40418. _this.radius = radius;
  40419. _this.tessellation = tessellation;
  40420. _this.side = side;
  40421. return _this;
  40422. }
  40423. /** @hidden */
  40424. DiscGeometry.prototype._regenerateVertexData = function () {
  40425. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40426. };
  40427. DiscGeometry.prototype.copy = function (id) {
  40428. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40429. };
  40430. return DiscGeometry;
  40431. }(_PrimitiveGeometry));
  40432. BABYLON.DiscGeometry = DiscGeometry;
  40433. /**
  40434. * Creates a new cylinder geometry
  40435. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40436. */
  40437. var CylinderGeometry = /** @class */ (function (_super) {
  40438. __extends(CylinderGeometry, _super);
  40439. /**
  40440. * Creates a new cylinder geometry
  40441. * @param id defines the unique ID of the geometry
  40442. * @param scene defines the hosting scene
  40443. * @param height defines the height of the cylinder
  40444. * @param diameterTop defines the diameter of the cylinder's top cap
  40445. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40446. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40447. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40448. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40449. * @param mesh defines the hosting mesh (can be null)
  40450. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40451. */
  40452. function CylinderGeometry(id, scene,
  40453. /**
  40454. * Defines the height of the cylinder
  40455. */
  40456. height,
  40457. /**
  40458. * Defines the diameter of the cylinder's top cap
  40459. */
  40460. diameterTop,
  40461. /**
  40462. * Defines the diameter of the cylinder's bottom cap
  40463. */
  40464. diameterBottom,
  40465. /**
  40466. * Defines the tessellation factor to apply to the cylinder
  40467. */
  40468. tessellation,
  40469. /**
  40470. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40471. */
  40472. subdivisions, canBeRegenerated, mesh,
  40473. /**
  40474. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40475. */
  40476. side) {
  40477. if (subdivisions === void 0) { subdivisions = 1; }
  40478. if (mesh === void 0) { mesh = null; }
  40479. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40480. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40481. _this.height = height;
  40482. _this.diameterTop = diameterTop;
  40483. _this.diameterBottom = diameterBottom;
  40484. _this.tessellation = tessellation;
  40485. _this.subdivisions = subdivisions;
  40486. _this.side = side;
  40487. return _this;
  40488. }
  40489. /** @hidden */
  40490. CylinderGeometry.prototype._regenerateVertexData = function () {
  40491. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40492. };
  40493. CylinderGeometry.prototype.copy = function (id) {
  40494. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40495. };
  40496. CylinderGeometry.prototype.serialize = function () {
  40497. var serializationObject = _super.prototype.serialize.call(this);
  40498. serializationObject.height = this.height;
  40499. serializationObject.diameterTop = this.diameterTop;
  40500. serializationObject.diameterBottom = this.diameterBottom;
  40501. serializationObject.tessellation = this.tessellation;
  40502. return serializationObject;
  40503. };
  40504. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40505. if (scene.getGeometryByID(parsedCylinder.id)) {
  40506. return null; // null since geometry could be something else than a cylinder...
  40507. }
  40508. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40509. if (BABYLON.Tags) {
  40510. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40511. }
  40512. scene.pushGeometry(cylinder, true);
  40513. return cylinder;
  40514. };
  40515. return CylinderGeometry;
  40516. }(_PrimitiveGeometry));
  40517. BABYLON.CylinderGeometry = CylinderGeometry;
  40518. /**
  40519. * Creates a new torus geometry
  40520. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40521. */
  40522. var TorusGeometry = /** @class */ (function (_super) {
  40523. __extends(TorusGeometry, _super);
  40524. /**
  40525. * Creates a new torus geometry
  40526. * @param id defines the unique ID of the geometry
  40527. * @param scene defines the hosting scene
  40528. * @param diameter defines the diameter of the torus
  40529. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40530. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40531. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40532. * @param mesh defines the hosting mesh (can be null)
  40533. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40534. */
  40535. function TorusGeometry(id, scene,
  40536. /**
  40537. * Defines the diameter of the torus
  40538. */
  40539. diameter,
  40540. /**
  40541. * Defines the thickness of the torus (ie. internal diameter)
  40542. */
  40543. thickness,
  40544. /**
  40545. * Defines the tesselation factor to apply to the torus
  40546. */
  40547. tessellation, canBeRegenerated, mesh,
  40548. /**
  40549. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40550. */
  40551. side) {
  40552. if (mesh === void 0) { mesh = null; }
  40553. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40554. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40555. _this.diameter = diameter;
  40556. _this.thickness = thickness;
  40557. _this.tessellation = tessellation;
  40558. _this.side = side;
  40559. return _this;
  40560. }
  40561. /** @hidden */
  40562. TorusGeometry.prototype._regenerateVertexData = function () {
  40563. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40564. };
  40565. TorusGeometry.prototype.copy = function (id) {
  40566. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40567. };
  40568. TorusGeometry.prototype.serialize = function () {
  40569. var serializationObject = _super.prototype.serialize.call(this);
  40570. serializationObject.diameter = this.diameter;
  40571. serializationObject.thickness = this.thickness;
  40572. serializationObject.tessellation = this.tessellation;
  40573. return serializationObject;
  40574. };
  40575. TorusGeometry.Parse = function (parsedTorus, scene) {
  40576. if (scene.getGeometryByID(parsedTorus.id)) {
  40577. return null; // null since geometry could be something else than a torus...
  40578. }
  40579. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40580. if (BABYLON.Tags) {
  40581. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40582. }
  40583. scene.pushGeometry(torus, true);
  40584. return torus;
  40585. };
  40586. return TorusGeometry;
  40587. }(_PrimitiveGeometry));
  40588. BABYLON.TorusGeometry = TorusGeometry;
  40589. /**
  40590. * Creates a new ground geometry
  40591. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40592. */
  40593. var GroundGeometry = /** @class */ (function (_super) {
  40594. __extends(GroundGeometry, _super);
  40595. /**
  40596. * Creates a new ground geometry
  40597. * @param id defines the unique ID of the geometry
  40598. * @param scene defines the hosting scene
  40599. * @param width defines the width of the ground
  40600. * @param height defines the height of the ground
  40601. * @param subdivisions defines the subdivisions to apply to the ground
  40602. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40603. * @param mesh defines the hosting mesh (can be null)
  40604. */
  40605. function GroundGeometry(id, scene,
  40606. /**
  40607. * Defines the width of the ground
  40608. */
  40609. width,
  40610. /**
  40611. * Defines the height of the ground
  40612. */
  40613. height,
  40614. /**
  40615. * Defines the subdivisions to apply to the ground
  40616. */
  40617. subdivisions, canBeRegenerated, mesh) {
  40618. if (mesh === void 0) { mesh = null; }
  40619. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40620. _this.width = width;
  40621. _this.height = height;
  40622. _this.subdivisions = subdivisions;
  40623. return _this;
  40624. }
  40625. /** @hidden */
  40626. GroundGeometry.prototype._regenerateVertexData = function () {
  40627. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40628. };
  40629. GroundGeometry.prototype.copy = function (id) {
  40630. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40631. };
  40632. GroundGeometry.prototype.serialize = function () {
  40633. var serializationObject = _super.prototype.serialize.call(this);
  40634. serializationObject.width = this.width;
  40635. serializationObject.height = this.height;
  40636. serializationObject.subdivisions = this.subdivisions;
  40637. return serializationObject;
  40638. };
  40639. GroundGeometry.Parse = function (parsedGround, scene) {
  40640. if (scene.getGeometryByID(parsedGround.id)) {
  40641. return null; // null since geometry could be something else than a ground...
  40642. }
  40643. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40644. if (BABYLON.Tags) {
  40645. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40646. }
  40647. scene.pushGeometry(ground, true);
  40648. return ground;
  40649. };
  40650. return GroundGeometry;
  40651. }(_PrimitiveGeometry));
  40652. BABYLON.GroundGeometry = GroundGeometry;
  40653. /**
  40654. * Creates a tiled ground geometry
  40655. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40656. */
  40657. var TiledGroundGeometry = /** @class */ (function (_super) {
  40658. __extends(TiledGroundGeometry, _super);
  40659. /**
  40660. * Creates a tiled ground geometry
  40661. * @param id defines the unique ID of the geometry
  40662. * @param scene defines the hosting scene
  40663. * @param xmin defines the minimum value on X axis
  40664. * @param zmin defines the minimum value on Z axis
  40665. * @param xmax defines the maximum value on X axis
  40666. * @param zmax defines the maximum value on Z axis
  40667. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40668. * @param precision defines the precision to use when computing the tiles
  40669. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40670. * @param mesh defines the hosting mesh (can be null)
  40671. */
  40672. function TiledGroundGeometry(id, scene,
  40673. /**
  40674. * Defines the minimum value on X axis
  40675. */
  40676. xmin,
  40677. /**
  40678. * Defines the minimum value on Z axis
  40679. */
  40680. zmin,
  40681. /**
  40682. * Defines the maximum value on X axis
  40683. */
  40684. xmax,
  40685. /**
  40686. * Defines the maximum value on Z axis
  40687. */
  40688. zmax,
  40689. /**
  40690. * Defines the subdivisions to apply to the ground
  40691. */
  40692. subdivisions,
  40693. /**
  40694. * Defines the precision to use when computing the tiles
  40695. */
  40696. precision, canBeRegenerated, mesh) {
  40697. if (mesh === void 0) { mesh = null; }
  40698. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40699. _this.xmin = xmin;
  40700. _this.zmin = zmin;
  40701. _this.xmax = xmax;
  40702. _this.zmax = zmax;
  40703. _this.subdivisions = subdivisions;
  40704. _this.precision = precision;
  40705. return _this;
  40706. }
  40707. /** @hidden */
  40708. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40709. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40710. };
  40711. TiledGroundGeometry.prototype.copy = function (id) {
  40712. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40713. };
  40714. return TiledGroundGeometry;
  40715. }(_PrimitiveGeometry));
  40716. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40717. /**
  40718. * Creates a plane geometry
  40719. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40720. */
  40721. var PlaneGeometry = /** @class */ (function (_super) {
  40722. __extends(PlaneGeometry, _super);
  40723. /**
  40724. * Creates a plane geometry
  40725. * @param id defines the unique ID of the geometry
  40726. * @param scene defines the hosting scene
  40727. * @param size defines the size of the plane (width === height)
  40728. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40729. * @param mesh defines the hosting mesh (can be null)
  40730. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40731. */
  40732. function PlaneGeometry(id, scene,
  40733. /**
  40734. * Defines the size of the plane (width === height)
  40735. */
  40736. size, canBeRegenerated, mesh,
  40737. /**
  40738. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40739. */
  40740. side) {
  40741. if (mesh === void 0) { mesh = null; }
  40742. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40743. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40744. _this.size = size;
  40745. _this.side = side;
  40746. return _this;
  40747. }
  40748. /** @hidden */
  40749. PlaneGeometry.prototype._regenerateVertexData = function () {
  40750. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40751. };
  40752. PlaneGeometry.prototype.copy = function (id) {
  40753. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40754. };
  40755. PlaneGeometry.prototype.serialize = function () {
  40756. var serializationObject = _super.prototype.serialize.call(this);
  40757. serializationObject.size = this.size;
  40758. return serializationObject;
  40759. };
  40760. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40761. if (scene.getGeometryByID(parsedPlane.id)) {
  40762. return null; // null since geometry could be something else than a ground...
  40763. }
  40764. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40765. if (BABYLON.Tags) {
  40766. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40767. }
  40768. scene.pushGeometry(plane, true);
  40769. return plane;
  40770. };
  40771. return PlaneGeometry;
  40772. }(_PrimitiveGeometry));
  40773. BABYLON.PlaneGeometry = PlaneGeometry;
  40774. /**
  40775. * Creates a torus knot geometry
  40776. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40777. */
  40778. var TorusKnotGeometry = /** @class */ (function (_super) {
  40779. __extends(TorusKnotGeometry, _super);
  40780. /**
  40781. * Creates a torus knot geometry
  40782. * @param id defines the unique ID of the geometry
  40783. * @param scene defines the hosting scene
  40784. * @param radius defines the radius of the torus knot
  40785. * @param tube defines the thickness of the torus knot tube
  40786. * @param radialSegments defines the number of radial segments
  40787. * @param tubularSegments defines the number of tubular segments
  40788. * @param p defines the first number of windings
  40789. * @param q defines the second number of windings
  40790. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40791. * @param mesh defines the hosting mesh (can be null)
  40792. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40793. */
  40794. function TorusKnotGeometry(id, scene,
  40795. /**
  40796. * Defines the radius of the torus knot
  40797. */
  40798. radius,
  40799. /**
  40800. * Defines the thickness of the torus knot tube
  40801. */
  40802. tube,
  40803. /**
  40804. * Defines the number of radial segments
  40805. */
  40806. radialSegments,
  40807. /**
  40808. * Defines the number of tubular segments
  40809. */
  40810. tubularSegments,
  40811. /**
  40812. * Defines the first number of windings
  40813. */
  40814. p,
  40815. /**
  40816. * Defines the second number of windings
  40817. */
  40818. q, canBeRegenerated, mesh,
  40819. /**
  40820. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40821. */
  40822. side) {
  40823. if (mesh === void 0) { mesh = null; }
  40824. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40825. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40826. _this.radius = radius;
  40827. _this.tube = tube;
  40828. _this.radialSegments = radialSegments;
  40829. _this.tubularSegments = tubularSegments;
  40830. _this.p = p;
  40831. _this.q = q;
  40832. _this.side = side;
  40833. return _this;
  40834. }
  40835. /** @hidden */
  40836. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40837. 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 });
  40838. };
  40839. TorusKnotGeometry.prototype.copy = function (id) {
  40840. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40841. };
  40842. TorusKnotGeometry.prototype.serialize = function () {
  40843. var serializationObject = _super.prototype.serialize.call(this);
  40844. serializationObject.radius = this.radius;
  40845. serializationObject.tube = this.tube;
  40846. serializationObject.radialSegments = this.radialSegments;
  40847. serializationObject.tubularSegments = this.tubularSegments;
  40848. serializationObject.p = this.p;
  40849. serializationObject.q = this.q;
  40850. return serializationObject;
  40851. };
  40852. ;
  40853. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40854. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40855. return null; // null since geometry could be something else than a ground...
  40856. }
  40857. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40858. if (BABYLON.Tags) {
  40859. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40860. }
  40861. scene.pushGeometry(torusKnot, true);
  40862. return torusKnot;
  40863. };
  40864. return TorusKnotGeometry;
  40865. }(_PrimitiveGeometry));
  40866. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40867. //}
  40868. })(BABYLON || (BABYLON = {}));
  40869. //# sourceMappingURL=babylon.geometry.js.map
  40870. var BABYLON;
  40871. (function (BABYLON) {
  40872. /**
  40873. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40874. */
  40875. var PerformanceMonitor = /** @class */ (function () {
  40876. /**
  40877. * constructor
  40878. * @param frameSampleSize The number of samples required to saturate the sliding window
  40879. */
  40880. function PerformanceMonitor(frameSampleSize) {
  40881. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40882. this._enabled = true;
  40883. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40884. }
  40885. /**
  40886. * Samples current frame
  40887. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40888. */
  40889. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40890. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40891. if (!this._enabled)
  40892. return;
  40893. if (this._lastFrameTimeMs != null) {
  40894. var dt = timeMs - this._lastFrameTimeMs;
  40895. this._rollingFrameTime.add(dt);
  40896. }
  40897. this._lastFrameTimeMs = timeMs;
  40898. };
  40899. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40900. /**
  40901. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40902. * @return Average frame time in milliseconds
  40903. */
  40904. get: function () {
  40905. return this._rollingFrameTime.average;
  40906. },
  40907. enumerable: true,
  40908. configurable: true
  40909. });
  40910. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40911. /**
  40912. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40913. * @return Frame time variance in milliseconds squared
  40914. */
  40915. get: function () {
  40916. return this._rollingFrameTime.variance;
  40917. },
  40918. enumerable: true,
  40919. configurable: true
  40920. });
  40921. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40922. /**
  40923. * Returns the frame time of the most recent frame
  40924. * @return Frame time in milliseconds
  40925. */
  40926. get: function () {
  40927. return this._rollingFrameTime.history(0);
  40928. },
  40929. enumerable: true,
  40930. configurable: true
  40931. });
  40932. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40933. /**
  40934. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40935. * @return Framerate in frames per second
  40936. */
  40937. get: function () {
  40938. return 1000.0 / this._rollingFrameTime.average;
  40939. },
  40940. enumerable: true,
  40941. configurable: true
  40942. });
  40943. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40944. /**
  40945. * Returns the average framerate in frames per second using the most recent frame time
  40946. * @return Framerate in frames per second
  40947. */
  40948. get: function () {
  40949. var history = this._rollingFrameTime.history(0);
  40950. if (history === 0) {
  40951. return 0;
  40952. }
  40953. return 1000.0 / history;
  40954. },
  40955. enumerable: true,
  40956. configurable: true
  40957. });
  40958. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40959. /**
  40960. * Returns true if enough samples have been taken to completely fill the sliding window
  40961. * @return true if saturated
  40962. */
  40963. get: function () {
  40964. return this._rollingFrameTime.isSaturated();
  40965. },
  40966. enumerable: true,
  40967. configurable: true
  40968. });
  40969. /**
  40970. * Enables contributions to the sliding window sample set
  40971. */
  40972. PerformanceMonitor.prototype.enable = function () {
  40973. this._enabled = true;
  40974. };
  40975. /**
  40976. * Disables contributions to the sliding window sample set
  40977. * Samples will not be interpolated over the disabled period
  40978. */
  40979. PerformanceMonitor.prototype.disable = function () {
  40980. this._enabled = false;
  40981. //clear last sample to avoid interpolating over the disabled period when next enabled
  40982. this._lastFrameTimeMs = null;
  40983. };
  40984. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40985. /**
  40986. * Returns true if sampling is enabled
  40987. * @return true if enabled
  40988. */
  40989. get: function () {
  40990. return this._enabled;
  40991. },
  40992. enumerable: true,
  40993. configurable: true
  40994. });
  40995. /**
  40996. * Resets performance monitor
  40997. */
  40998. PerformanceMonitor.prototype.reset = function () {
  40999. //clear last sample to avoid interpolating over the disabled period when next enabled
  41000. this._lastFrameTimeMs = null;
  41001. //wipe record
  41002. this._rollingFrameTime.reset();
  41003. };
  41004. return PerformanceMonitor;
  41005. }());
  41006. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41007. /**
  41008. * RollingAverage
  41009. *
  41010. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41011. */
  41012. var RollingAverage = /** @class */ (function () {
  41013. /**
  41014. * constructor
  41015. * @param length The number of samples required to saturate the sliding window
  41016. */
  41017. function RollingAverage(length) {
  41018. this._samples = new Array(length);
  41019. this.reset();
  41020. }
  41021. /**
  41022. * Adds a sample to the sample set
  41023. * @param v The sample value
  41024. */
  41025. RollingAverage.prototype.add = function (v) {
  41026. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41027. var delta;
  41028. //we need to check if we've already wrapped round
  41029. if (this.isSaturated()) {
  41030. //remove bottom of stack from mean
  41031. var bottomValue = this._samples[this._pos];
  41032. delta = bottomValue - this.average;
  41033. this.average -= delta / (this._sampleCount - 1);
  41034. this._m2 -= delta * (bottomValue - this.average);
  41035. }
  41036. else {
  41037. this._sampleCount++;
  41038. }
  41039. //add new value to mean
  41040. delta = v - this.average;
  41041. this.average += delta / (this._sampleCount);
  41042. this._m2 += delta * (v - this.average);
  41043. //set the new variance
  41044. this.variance = this._m2 / (this._sampleCount - 1);
  41045. this._samples[this._pos] = v;
  41046. this._pos++;
  41047. this._pos %= this._samples.length; //positive wrap around
  41048. };
  41049. /**
  41050. * Returns previously added values or null if outside of history or outside the sliding window domain
  41051. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41052. * @return Value previously recorded with add() or null if outside of range
  41053. */
  41054. RollingAverage.prototype.history = function (i) {
  41055. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41056. return 0;
  41057. }
  41058. var i0 = this._wrapPosition(this._pos - 1.0);
  41059. return this._samples[this._wrapPosition(i0 - i)];
  41060. };
  41061. /**
  41062. * Returns true if enough samples have been taken to completely fill the sliding window
  41063. * @return true if sample-set saturated
  41064. */
  41065. RollingAverage.prototype.isSaturated = function () {
  41066. return this._sampleCount >= this._samples.length;
  41067. };
  41068. /**
  41069. * Resets the rolling average (equivalent to 0 samples taken so far)
  41070. */
  41071. RollingAverage.prototype.reset = function () {
  41072. this.average = 0;
  41073. this.variance = 0;
  41074. this._sampleCount = 0;
  41075. this._pos = 0;
  41076. this._m2 = 0;
  41077. };
  41078. /**
  41079. * Wraps a value around the sample range boundaries
  41080. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41081. * @return Wrapped position in sample range
  41082. */
  41083. RollingAverage.prototype._wrapPosition = function (i) {
  41084. var max = this._samples.length;
  41085. return ((i % max) + max) % max;
  41086. };
  41087. return RollingAverage;
  41088. }());
  41089. BABYLON.RollingAverage = RollingAverage;
  41090. })(BABYLON || (BABYLON = {}));
  41091. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41092. var BABYLON;
  41093. (function (BABYLON) {
  41094. /**
  41095. * "Static Class" containing the most commonly used helper while dealing with material for
  41096. * rendering purpose.
  41097. *
  41098. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41099. *
  41100. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41101. */
  41102. var MaterialHelper = /** @class */ (function () {
  41103. function MaterialHelper() {
  41104. }
  41105. /**
  41106. * Bind the current view position to an effect.
  41107. * @param effect The effect to be bound
  41108. * @param scene The scene the eyes position is used from
  41109. */
  41110. MaterialHelper.BindEyePosition = function (effect, scene) {
  41111. if (scene._forcedViewPosition) {
  41112. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41113. return;
  41114. }
  41115. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41116. };
  41117. /**
  41118. * Helps preparing the defines values about the UVs in used in the effect.
  41119. * UVs are shared as much as we can accross chanels in the shaders.
  41120. * @param texture The texture we are preparing the UVs for
  41121. * @param defines The defines to update
  41122. * @param key The chanel key "diffuse", "specular"... used in the shader
  41123. */
  41124. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41125. defines._needUVs = true;
  41126. defines[key] = true;
  41127. if (texture.getTextureMatrix().isIdentity(true)) {
  41128. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41129. if (texture.coordinatesIndex === 0) {
  41130. defines["MAINUV1"] = true;
  41131. }
  41132. else {
  41133. defines["MAINUV2"] = true;
  41134. }
  41135. }
  41136. else {
  41137. defines[key + "DIRECTUV"] = 0;
  41138. }
  41139. };
  41140. /**
  41141. * Binds a texture matrix value to its corrsponding uniform
  41142. * @param texture The texture to bind the matrix for
  41143. * @param uniformBuffer The uniform buffer receivin the data
  41144. * @param key The chanel key "diffuse", "specular"... used in the shader
  41145. */
  41146. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41147. var matrix = texture.getTextureMatrix();
  41148. if (!matrix.isIdentity(true)) {
  41149. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41150. }
  41151. };
  41152. /**
  41153. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41154. * @param mesh defines the current mesh
  41155. * @param scene defines the current scene
  41156. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41157. * @param pointsCloud defines if point cloud rendering has to be turned on
  41158. * @param fogEnabled defines if fog has to be turned on
  41159. * @param alphaTest defines if alpha testing has to be turned on
  41160. * @param defines defines the current list of defines
  41161. */
  41162. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41163. if (defines._areMiscDirty) {
  41164. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41165. defines["POINTSIZE"] = pointsCloud;
  41166. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41167. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41168. defines["ALPHATEST"] = alphaTest;
  41169. }
  41170. };
  41171. /**
  41172. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41173. * @param scene defines the current scene
  41174. * @param engine defines the current engine
  41175. * @param defines specifies the list of active defines
  41176. * @param useInstances defines if instances have to be turned on
  41177. * @param useClipPlane defines if clip plane have to be turned on
  41178. */
  41179. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41180. if (useClipPlane === void 0) { useClipPlane = null; }
  41181. var changed = false;
  41182. var useClipPlane1 = false;
  41183. var useClipPlane2 = false;
  41184. var useClipPlane3 = false;
  41185. var useClipPlane4 = false;
  41186. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  41187. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  41188. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  41189. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  41190. if (defines["CLIPPLANE"] !== useClipPlane1) {
  41191. defines["CLIPPLANE"] = useClipPlane1;
  41192. changed = true;
  41193. }
  41194. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  41195. defines["CLIPPLANE2"] = useClipPlane2;
  41196. changed = true;
  41197. }
  41198. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  41199. defines["CLIPPLANE3"] = useClipPlane3;
  41200. changed = true;
  41201. }
  41202. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  41203. defines["CLIPPLANE4"] = useClipPlane4;
  41204. changed = true;
  41205. }
  41206. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41207. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41208. changed = true;
  41209. }
  41210. if (defines["INSTANCES"] !== useInstances) {
  41211. defines["INSTANCES"] = useInstances;
  41212. changed = true;
  41213. }
  41214. if (changed) {
  41215. defines.markAsUnprocessed();
  41216. }
  41217. };
  41218. /**
  41219. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41220. * @param mesh The mesh containing the geometry data we will draw
  41221. * @param defines The defines to update
  41222. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41223. * @param useBones Precise whether bones should be used or not (override mesh info)
  41224. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41225. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41226. * @returns false if defines are considered not dirty and have not been checked
  41227. */
  41228. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41229. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41230. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41231. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41232. return false;
  41233. }
  41234. defines._normals = defines._needNormals;
  41235. defines._uvs = defines._needUVs;
  41236. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41237. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41238. defines["TANGENT"] = true;
  41239. }
  41240. if (defines._needUVs) {
  41241. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41242. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41243. }
  41244. else {
  41245. defines["UV1"] = false;
  41246. defines["UV2"] = false;
  41247. }
  41248. if (useVertexColor) {
  41249. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41250. defines["VERTEXCOLOR"] = hasVertexColors;
  41251. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41252. }
  41253. if (useBones) {
  41254. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41255. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41256. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41257. }
  41258. else {
  41259. defines["NUM_BONE_INFLUENCERS"] = 0;
  41260. defines["BonesPerMesh"] = 0;
  41261. }
  41262. }
  41263. if (useMorphTargets) {
  41264. var manager = mesh.morphTargetManager;
  41265. if (manager) {
  41266. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41267. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41268. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41269. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41270. }
  41271. else {
  41272. defines["MORPHTARGETS_TANGENT"] = false;
  41273. defines["MORPHTARGETS_NORMAL"] = false;
  41274. defines["MORPHTARGETS"] = false;
  41275. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41276. }
  41277. }
  41278. return true;
  41279. };
  41280. /**
  41281. * Prepares the defines related to the light information passed in parameter
  41282. * @param scene The scene we are intending to draw
  41283. * @param mesh The mesh the effect is compiling for
  41284. * @param defines The defines to update
  41285. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41286. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41287. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41288. * @returns true if normals will be required for the rest of the effect
  41289. */
  41290. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41291. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41292. if (disableLighting === void 0) { disableLighting = false; }
  41293. if (!defines._areLightsDirty) {
  41294. return defines._needNormals;
  41295. }
  41296. var lightIndex = 0;
  41297. var needNormals = false;
  41298. var needRebuild = false;
  41299. var lightmapMode = false;
  41300. var shadowEnabled = false;
  41301. var specularEnabled = false;
  41302. if (scene.lightsEnabled && !disableLighting) {
  41303. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41304. var light = _a[_i];
  41305. needNormals = true;
  41306. if (defines["LIGHT" + lightIndex] === undefined) {
  41307. needRebuild = true;
  41308. }
  41309. defines["LIGHT" + lightIndex] = true;
  41310. defines["SPOTLIGHT" + lightIndex] = false;
  41311. defines["HEMILIGHT" + lightIndex] = false;
  41312. defines["POINTLIGHT" + lightIndex] = false;
  41313. defines["DIRLIGHT" + lightIndex] = false;
  41314. light.prepareLightSpecificDefines(defines, lightIndex);
  41315. // FallOff.
  41316. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  41317. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  41318. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  41319. switch (light.falloffType) {
  41320. case BABYLON.Light.FALLOFF_GLTF:
  41321. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  41322. break;
  41323. case BABYLON.Light.FALLOFF_PHYSICAL:
  41324. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  41325. break;
  41326. case BABYLON.Light.FALLOFF_STANDARD:
  41327. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  41328. break;
  41329. }
  41330. // Specular
  41331. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41332. specularEnabled = true;
  41333. }
  41334. // Shadows
  41335. defines["SHADOW" + lightIndex] = false;
  41336. defines["SHADOWPCF" + lightIndex] = false;
  41337. defines["SHADOWPCSS" + lightIndex] = false;
  41338. defines["SHADOWPOISSON" + lightIndex] = false;
  41339. defines["SHADOWESM" + lightIndex] = false;
  41340. defines["SHADOWCUBE" + lightIndex] = false;
  41341. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41342. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41343. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41344. var shadowGenerator = light.getShadowGenerator();
  41345. if (shadowGenerator) {
  41346. var shadowMap = shadowGenerator.getShadowMap();
  41347. if (shadowMap) {
  41348. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  41349. shadowEnabled = true;
  41350. shadowGenerator.prepareDefines(defines, lightIndex);
  41351. }
  41352. }
  41353. }
  41354. }
  41355. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41356. lightmapMode = true;
  41357. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41358. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41359. }
  41360. else {
  41361. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41362. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41363. }
  41364. lightIndex++;
  41365. if (lightIndex === maxSimultaneousLights)
  41366. break;
  41367. }
  41368. }
  41369. defines["SPECULARTERM"] = specularEnabled;
  41370. defines["SHADOWS"] = shadowEnabled;
  41371. // Resetting all other lights if any
  41372. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41373. if (defines["LIGHT" + index] !== undefined) {
  41374. defines["LIGHT" + index] = false;
  41375. defines["HEMILIGHT" + lightIndex] = false;
  41376. defines["POINTLIGHT" + lightIndex] = false;
  41377. defines["DIRLIGHT" + lightIndex] = false;
  41378. defines["SPOTLIGHT" + lightIndex] = false;
  41379. defines["SHADOW" + lightIndex] = false;
  41380. }
  41381. }
  41382. var caps = scene.getEngine().getCaps();
  41383. if (defines["SHADOWFLOAT"] === undefined) {
  41384. needRebuild = true;
  41385. }
  41386. defines["SHADOWFLOAT"] = shadowEnabled &&
  41387. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41388. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41389. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41390. if (needRebuild) {
  41391. defines.rebuild();
  41392. }
  41393. return needNormals;
  41394. };
  41395. /**
  41396. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41397. * that won t be acctive due to defines being turned off.
  41398. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41399. * @param samplersList The samplers list
  41400. * @param defines The defines helping in the list generation
  41401. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41402. */
  41403. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41404. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41405. var uniformsList;
  41406. var uniformBuffersList = null;
  41407. if (uniformsListOrOptions.uniformsNames) {
  41408. var options = uniformsListOrOptions;
  41409. uniformsList = options.uniformsNames;
  41410. uniformBuffersList = options.uniformBuffersNames;
  41411. samplersList = options.samplers;
  41412. defines = options.defines;
  41413. maxSimultaneousLights = options.maxSimultaneousLights;
  41414. }
  41415. else {
  41416. uniformsList = uniformsListOrOptions;
  41417. if (!samplersList) {
  41418. samplersList = [];
  41419. }
  41420. }
  41421. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41422. if (!defines["LIGHT" + lightIndex]) {
  41423. break;
  41424. }
  41425. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41426. if (uniformBuffersList) {
  41427. uniformBuffersList.push("Light" + lightIndex);
  41428. }
  41429. samplersList.push("shadowSampler" + lightIndex);
  41430. samplersList.push("depthSampler" + lightIndex);
  41431. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41432. samplersList.push("projectionLightSampler" + lightIndex);
  41433. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41434. }
  41435. }
  41436. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41437. uniformsList.push("morphTargetInfluences");
  41438. }
  41439. };
  41440. /**
  41441. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41442. * @param defines The defines to update while falling back
  41443. * @param fallbacks The authorized effect fallbacks
  41444. * @param maxSimultaneousLights The maximum number of lights allowed
  41445. * @param rank the current rank of the Effect
  41446. * @returns The newly affected rank
  41447. */
  41448. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41449. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41450. if (rank === void 0) { rank = 0; }
  41451. var lightFallbackRank = 0;
  41452. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41453. if (!defines["LIGHT" + lightIndex]) {
  41454. break;
  41455. }
  41456. if (lightIndex > 0) {
  41457. lightFallbackRank = rank + lightIndex;
  41458. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41459. }
  41460. if (!defines["SHADOWS"]) {
  41461. if (defines["SHADOW" + lightIndex]) {
  41462. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41463. }
  41464. if (defines["SHADOWPCF" + lightIndex]) {
  41465. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41466. }
  41467. if (defines["SHADOWPCSS" + lightIndex]) {
  41468. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41469. }
  41470. if (defines["SHADOWPOISSON" + lightIndex]) {
  41471. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41472. }
  41473. if (defines["SHADOWESM" + lightIndex]) {
  41474. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41475. }
  41476. }
  41477. }
  41478. return lightFallbackRank++;
  41479. };
  41480. /**
  41481. * Prepares the list of attributes required for morph targets according to the effect defines.
  41482. * @param attribs The current list of supported attribs
  41483. * @param mesh The mesh to prepare the morph targets attributes for
  41484. * @param defines The current Defines of the effect
  41485. */
  41486. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41487. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41488. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41489. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41490. var manager = mesh.morphTargetManager;
  41491. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41492. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41493. for (var index = 0; index < influencers; index++) {
  41494. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41495. if (normal) {
  41496. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41497. }
  41498. if (tangent) {
  41499. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41500. }
  41501. if (attribs.length > maxAttributesCount) {
  41502. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41503. }
  41504. }
  41505. }
  41506. };
  41507. /**
  41508. * Prepares the list of attributes required for bones according to the effect defines.
  41509. * @param attribs The current list of supported attribs
  41510. * @param mesh The mesh to prepare the bones attributes for
  41511. * @param defines The current Defines of the effect
  41512. * @param fallbacks The current efffect fallback strategy
  41513. */
  41514. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41515. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41516. fallbacks.addCPUSkinningFallback(0, mesh);
  41517. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41518. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41519. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41520. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41521. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41522. }
  41523. }
  41524. };
  41525. /**
  41526. * Prepares the list of attributes required for instances according to the effect defines.
  41527. * @param attribs The current list of supported attribs
  41528. * @param defines The current Defines of the effect
  41529. */
  41530. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41531. if (defines["INSTANCES"]) {
  41532. attribs.push("world0");
  41533. attribs.push("world1");
  41534. attribs.push("world2");
  41535. attribs.push("world3");
  41536. }
  41537. };
  41538. /**
  41539. * Binds the light shadow information to the effect for the given mesh.
  41540. * @param light The light containing the generator
  41541. * @param scene The scene the lights belongs to
  41542. * @param mesh The mesh we are binding the information to render
  41543. * @param lightIndex The light index in the effect used to render the mesh
  41544. * @param effect The effect we are binding the data to
  41545. */
  41546. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41547. if (light.shadowEnabled && mesh.receiveShadows) {
  41548. var shadowGenerator = light.getShadowGenerator();
  41549. if (shadowGenerator) {
  41550. shadowGenerator.bindShadowLight(lightIndex, effect);
  41551. }
  41552. }
  41553. };
  41554. /**
  41555. * Binds the light information to the effect.
  41556. * @param light The light containing the generator
  41557. * @param effect The effect we are binding the data to
  41558. * @param lightIndex The light index in the effect used to render
  41559. */
  41560. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41561. light.transferToEffect(effect, lightIndex + "");
  41562. };
  41563. /**
  41564. * Binds the lights information from the scene to the effect for the given mesh.
  41565. * @param scene The scene the lights belongs to
  41566. * @param mesh The mesh we are binding the information to render
  41567. * @param effect The effect we are binding the data to
  41568. * @param defines The generated defines for the effect
  41569. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41570. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41571. */
  41572. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41573. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41574. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41575. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41576. for (var i = 0; i < len; i++) {
  41577. var light = mesh._lightSources[i];
  41578. var iAsString = i.toString();
  41579. var scaledIntensity = light.getScaledIntensity();
  41580. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41581. MaterialHelper.BindLightProperties(light, effect, i);
  41582. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41583. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41584. if (defines["SPECULARTERM"]) {
  41585. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41586. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41587. }
  41588. // Shadows
  41589. if (scene.shadowsEnabled) {
  41590. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41591. }
  41592. light._uniformBuffer.update();
  41593. }
  41594. };
  41595. /**
  41596. * Binds the fog information from the scene to the effect for the given mesh.
  41597. * @param scene The scene the lights belongs to
  41598. * @param mesh The mesh we are binding the information to render
  41599. * @param effect The effect we are binding the data to
  41600. */
  41601. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41602. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41603. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41604. effect.setColor3("vFogColor", scene.fogColor);
  41605. }
  41606. };
  41607. /**
  41608. * Binds the bones information from the mesh to the effect.
  41609. * @param mesh The mesh we are binding the information to render
  41610. * @param effect The effect we are binding the data to
  41611. */
  41612. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41613. if (!effect || !mesh) {
  41614. return;
  41615. }
  41616. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41617. mesh.computeBonesUsingShaders = false;
  41618. }
  41619. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41620. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41621. if (matrices) {
  41622. effect.setMatrices("mBones", matrices);
  41623. }
  41624. }
  41625. };
  41626. /**
  41627. * Binds the morph targets information from the mesh to the effect.
  41628. * @param abstractMesh The mesh we are binding the information to render
  41629. * @param effect The effect we are binding the data to
  41630. */
  41631. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41632. var manager = abstractMesh.morphTargetManager;
  41633. if (!abstractMesh || !manager) {
  41634. return;
  41635. }
  41636. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41637. };
  41638. /**
  41639. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41640. * @param defines The generated defines used in the effect
  41641. * @param effect The effect we are binding the data to
  41642. * @param scene The scene we are willing to render with logarithmic scale for
  41643. */
  41644. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41645. if (defines["LOGARITHMICDEPTH"]) {
  41646. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41647. }
  41648. };
  41649. /**
  41650. * Binds the clip plane information from the scene to the effect.
  41651. * @param scene The scene the clip plane information are extracted from
  41652. * @param effect The effect we are binding the data to
  41653. */
  41654. MaterialHelper.BindClipPlane = function (effect, scene) {
  41655. if (scene.clipPlane) {
  41656. var clipPlane = scene.clipPlane;
  41657. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41658. }
  41659. if (scene.clipPlane2) {
  41660. var clipPlane = scene.clipPlane2;
  41661. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41662. }
  41663. if (scene.clipPlane3) {
  41664. var clipPlane = scene.clipPlane3;
  41665. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41666. }
  41667. if (scene.clipPlane4) {
  41668. var clipPlane = scene.clipPlane4;
  41669. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41670. }
  41671. };
  41672. return MaterialHelper;
  41673. }());
  41674. BABYLON.MaterialHelper = MaterialHelper;
  41675. })(BABYLON || (BABYLON = {}));
  41676. //# sourceMappingURL=babylon.materialHelper.js.map
  41677. var BABYLON;
  41678. (function (BABYLON) {
  41679. var PushMaterial = /** @class */ (function (_super) {
  41680. __extends(PushMaterial, _super);
  41681. function PushMaterial(name, scene) {
  41682. var _this = _super.call(this, name, scene) || this;
  41683. _this._normalMatrix = new BABYLON.Matrix();
  41684. _this.storeEffectOnSubMeshes = true;
  41685. return _this;
  41686. }
  41687. PushMaterial.prototype.getEffect = function () {
  41688. return this._activeEffect;
  41689. };
  41690. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41691. if (!mesh) {
  41692. return false;
  41693. }
  41694. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41695. return true;
  41696. }
  41697. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41698. };
  41699. /**
  41700. * Binds the given world matrix to the active effect
  41701. *
  41702. * @param world the matrix to bind
  41703. */
  41704. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41705. this._activeEffect.setMatrix("world", world);
  41706. };
  41707. /**
  41708. * Binds the given normal matrix to the active effect
  41709. *
  41710. * @param normalMatrix the matrix to bind
  41711. */
  41712. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41713. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41714. };
  41715. PushMaterial.prototype.bind = function (world, mesh) {
  41716. if (!mesh) {
  41717. return;
  41718. }
  41719. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41720. };
  41721. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41722. if (effect === void 0) { effect = null; }
  41723. _super.prototype._afterBind.call(this, mesh);
  41724. this.getScene()._cachedEffect = effect;
  41725. };
  41726. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41727. if (visibility === void 0) { visibility = 1; }
  41728. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41729. };
  41730. return PushMaterial;
  41731. }(BABYLON.Material));
  41732. BABYLON.PushMaterial = PushMaterial;
  41733. })(BABYLON || (BABYLON = {}));
  41734. //# sourceMappingURL=babylon.pushMaterial.js.map
  41735. var BABYLON;
  41736. (function (BABYLON) {
  41737. /** @hidden */
  41738. var StandardMaterialDefines = /** @class */ (function (_super) {
  41739. __extends(StandardMaterialDefines, _super);
  41740. function StandardMaterialDefines() {
  41741. var _this = _super.call(this) || this;
  41742. _this.MAINUV1 = false;
  41743. _this.MAINUV2 = false;
  41744. _this.DIFFUSE = false;
  41745. _this.DIFFUSEDIRECTUV = 0;
  41746. _this.AMBIENT = false;
  41747. _this.AMBIENTDIRECTUV = 0;
  41748. _this.OPACITY = false;
  41749. _this.OPACITYDIRECTUV = 0;
  41750. _this.OPACITYRGB = false;
  41751. _this.REFLECTION = false;
  41752. _this.EMISSIVE = false;
  41753. _this.EMISSIVEDIRECTUV = 0;
  41754. _this.SPECULAR = false;
  41755. _this.SPECULARDIRECTUV = 0;
  41756. _this.BUMP = false;
  41757. _this.BUMPDIRECTUV = 0;
  41758. _this.PARALLAX = false;
  41759. _this.PARALLAXOCCLUSION = false;
  41760. _this.SPECULAROVERALPHA = false;
  41761. _this.CLIPPLANE = false;
  41762. _this.CLIPPLANE2 = false;
  41763. _this.CLIPPLANE3 = false;
  41764. _this.CLIPPLANE4 = false;
  41765. _this.ALPHATEST = false;
  41766. _this.DEPTHPREPASS = false;
  41767. _this.ALPHAFROMDIFFUSE = false;
  41768. _this.POINTSIZE = false;
  41769. _this.FOG = false;
  41770. _this.SPECULARTERM = false;
  41771. _this.DIFFUSEFRESNEL = false;
  41772. _this.OPACITYFRESNEL = false;
  41773. _this.REFLECTIONFRESNEL = false;
  41774. _this.REFRACTIONFRESNEL = false;
  41775. _this.EMISSIVEFRESNEL = false;
  41776. _this.FRESNEL = false;
  41777. _this.NORMAL = false;
  41778. _this.UV1 = false;
  41779. _this.UV2 = false;
  41780. _this.VERTEXCOLOR = false;
  41781. _this.VERTEXALPHA = false;
  41782. _this.NUM_BONE_INFLUENCERS = 0;
  41783. _this.BonesPerMesh = 0;
  41784. _this.INSTANCES = false;
  41785. _this.GLOSSINESS = false;
  41786. _this.ROUGHNESS = false;
  41787. _this.EMISSIVEASILLUMINATION = false;
  41788. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41789. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41790. _this.LIGHTMAP = false;
  41791. _this.LIGHTMAPDIRECTUV = 0;
  41792. _this.OBJECTSPACE_NORMALMAP = false;
  41793. _this.USELIGHTMAPASSHADOWMAP = false;
  41794. _this.REFLECTIONMAP_3D = false;
  41795. _this.REFLECTIONMAP_SPHERICAL = false;
  41796. _this.REFLECTIONMAP_PLANAR = false;
  41797. _this.REFLECTIONMAP_CUBIC = false;
  41798. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41799. _this.REFLECTIONMAP_PROJECTION = false;
  41800. _this.REFLECTIONMAP_SKYBOX = false;
  41801. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  41802. _this.REFLECTIONMAP_EXPLICIT = false;
  41803. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41804. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41805. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41806. _this.INVERTCUBICMAP = false;
  41807. _this.LOGARITHMICDEPTH = false;
  41808. _this.REFRACTION = false;
  41809. _this.REFRACTIONMAP_3D = false;
  41810. _this.REFLECTIONOVERALPHA = false;
  41811. _this.TWOSIDEDLIGHTING = false;
  41812. _this.SHADOWFLOAT = false;
  41813. _this.MORPHTARGETS = false;
  41814. _this.MORPHTARGETS_NORMAL = false;
  41815. _this.MORPHTARGETS_TANGENT = false;
  41816. _this.NUM_MORPH_INFLUENCERS = 0;
  41817. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41818. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41819. _this.IMAGEPROCESSING = false;
  41820. _this.VIGNETTE = false;
  41821. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41822. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41823. _this.TONEMAPPING = false;
  41824. _this.TONEMAPPING_ACES = false;
  41825. _this.CONTRAST = false;
  41826. _this.COLORCURVES = false;
  41827. _this.COLORGRADING = false;
  41828. _this.COLORGRADING3D = false;
  41829. _this.SAMPLER3DGREENDEPTH = false;
  41830. _this.SAMPLER3DBGRMAP = false;
  41831. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41832. /**
  41833. * If the reflection texture on this material is in linear color space
  41834. * @hidden
  41835. */
  41836. _this.IS_REFLECTION_LINEAR = false;
  41837. /**
  41838. * If the refraction texture on this material is in linear color space
  41839. * @hidden
  41840. */
  41841. _this.IS_REFRACTION_LINEAR = false;
  41842. _this.EXPOSURE = false;
  41843. _this.rebuild();
  41844. return _this;
  41845. }
  41846. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41847. var modes = [
  41848. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41849. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41850. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41851. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41852. ];
  41853. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41854. var mode = modes_1[_i];
  41855. this[mode] = (mode === modeToEnable);
  41856. }
  41857. };
  41858. return StandardMaterialDefines;
  41859. }(BABYLON.MaterialDefines));
  41860. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41861. var StandardMaterial = /** @class */ (function (_super) {
  41862. __extends(StandardMaterial, _super);
  41863. function StandardMaterial(name, scene) {
  41864. var _this = _super.call(this, name, scene) || this;
  41865. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41866. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41867. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41868. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41869. _this.specularPower = 64;
  41870. _this._useAlphaFromDiffuseTexture = false;
  41871. _this._useEmissiveAsIllumination = false;
  41872. _this._linkEmissiveWithDiffuse = false;
  41873. _this._useSpecularOverAlpha = false;
  41874. _this._useReflectionOverAlpha = false;
  41875. _this._disableLighting = false;
  41876. _this._useObjectSpaceNormalMap = false;
  41877. _this._useParallax = false;
  41878. _this._useParallaxOcclusion = false;
  41879. _this.parallaxScaleBias = 0.05;
  41880. _this._roughness = 0;
  41881. _this.indexOfRefraction = 0.98;
  41882. _this.invertRefractionY = true;
  41883. /**
  41884. * Defines the alpha limits in alpha test mode
  41885. */
  41886. _this.alphaCutOff = 0.4;
  41887. _this._useLightmapAsShadowmap = false;
  41888. _this._useReflectionFresnelFromSpecular = false;
  41889. _this._useGlossinessFromSpecularMapAlpha = false;
  41890. _this._maxSimultaneousLights = 4;
  41891. /**
  41892. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41893. */
  41894. _this._invertNormalMapX = false;
  41895. /**
  41896. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41897. */
  41898. _this._invertNormalMapY = false;
  41899. /**
  41900. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41901. */
  41902. _this._twoSidedLighting = false;
  41903. _this._renderTargets = new BABYLON.SmartArray(16);
  41904. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41905. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41906. // Setup the default processing configuration to the scene.
  41907. _this._attachImageProcessingConfiguration(null);
  41908. _this.getRenderTargetTextures = function () {
  41909. _this._renderTargets.reset();
  41910. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41911. _this._renderTargets.push(_this._reflectionTexture);
  41912. }
  41913. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41914. _this._renderTargets.push(_this._refractionTexture);
  41915. }
  41916. return _this._renderTargets;
  41917. };
  41918. return _this;
  41919. }
  41920. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41921. /**
  41922. * Gets the image processing configuration used either in this material.
  41923. */
  41924. get: function () {
  41925. return this._imageProcessingConfiguration;
  41926. },
  41927. /**
  41928. * Sets the Default image processing configuration used either in the this material.
  41929. *
  41930. * If sets to null, the scene one is in use.
  41931. */
  41932. set: function (value) {
  41933. this._attachImageProcessingConfiguration(value);
  41934. // Ensure the effect will be rebuilt.
  41935. this._markAllSubMeshesAsTexturesDirty();
  41936. },
  41937. enumerable: true,
  41938. configurable: true
  41939. });
  41940. /**
  41941. * Attaches a new image processing configuration to the Standard Material.
  41942. * @param configuration
  41943. */
  41944. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41945. var _this = this;
  41946. if (configuration === this._imageProcessingConfiguration) {
  41947. return;
  41948. }
  41949. // Detaches observer.
  41950. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41951. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41952. }
  41953. // Pick the scene configuration if needed.
  41954. if (!configuration) {
  41955. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41956. }
  41957. else {
  41958. this._imageProcessingConfiguration = configuration;
  41959. }
  41960. // Attaches observer.
  41961. if (this._imageProcessingConfiguration) {
  41962. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41963. _this._markAllSubMeshesAsImageProcessingDirty();
  41964. });
  41965. }
  41966. };
  41967. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41968. /**
  41969. * Gets wether the color curves effect is enabled.
  41970. */
  41971. get: function () {
  41972. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41973. },
  41974. /**
  41975. * Sets wether the color curves effect is enabled.
  41976. */
  41977. set: function (value) {
  41978. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41979. },
  41980. enumerable: true,
  41981. configurable: true
  41982. });
  41983. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41984. /**
  41985. * Gets wether the color grading effect is enabled.
  41986. */
  41987. get: function () {
  41988. return this.imageProcessingConfiguration.colorGradingEnabled;
  41989. },
  41990. /**
  41991. * Gets wether the color grading effect is enabled.
  41992. */
  41993. set: function (value) {
  41994. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41995. },
  41996. enumerable: true,
  41997. configurable: true
  41998. });
  41999. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42000. /**
  42001. * Gets wether tonemapping is enabled or not.
  42002. */
  42003. get: function () {
  42004. return this._imageProcessingConfiguration.toneMappingEnabled;
  42005. },
  42006. /**
  42007. * Sets wether tonemapping is enabled or not
  42008. */
  42009. set: function (value) {
  42010. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42011. },
  42012. enumerable: true,
  42013. configurable: true
  42014. });
  42015. ;
  42016. ;
  42017. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42018. /**
  42019. * The camera exposure used on this material.
  42020. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42021. * This corresponds to a photographic exposure.
  42022. */
  42023. get: function () {
  42024. return this._imageProcessingConfiguration.exposure;
  42025. },
  42026. /**
  42027. * The camera exposure used on this material.
  42028. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42029. * This corresponds to a photographic exposure.
  42030. */
  42031. set: function (value) {
  42032. this._imageProcessingConfiguration.exposure = value;
  42033. },
  42034. enumerable: true,
  42035. configurable: true
  42036. });
  42037. ;
  42038. ;
  42039. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42040. /**
  42041. * Gets The camera contrast used on this material.
  42042. */
  42043. get: function () {
  42044. return this._imageProcessingConfiguration.contrast;
  42045. },
  42046. /**
  42047. * Sets The camera contrast used on this material.
  42048. */
  42049. set: function (value) {
  42050. this._imageProcessingConfiguration.contrast = value;
  42051. },
  42052. enumerable: true,
  42053. configurable: true
  42054. });
  42055. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42056. /**
  42057. * Gets the Color Grading 2D Lookup Texture.
  42058. */
  42059. get: function () {
  42060. return this._imageProcessingConfiguration.colorGradingTexture;
  42061. },
  42062. /**
  42063. * Sets the Color Grading 2D Lookup Texture.
  42064. */
  42065. set: function (value) {
  42066. this._imageProcessingConfiguration.colorGradingTexture = value;
  42067. },
  42068. enumerable: true,
  42069. configurable: true
  42070. });
  42071. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42072. /**
  42073. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42074. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42075. * 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;
  42076. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42077. */
  42078. get: function () {
  42079. return this._imageProcessingConfiguration.colorCurves;
  42080. },
  42081. /**
  42082. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42083. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42084. * 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;
  42085. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42086. */
  42087. set: function (value) {
  42088. this._imageProcessingConfiguration.colorCurves = value;
  42089. },
  42090. enumerable: true,
  42091. configurable: true
  42092. });
  42093. StandardMaterial.prototype.getClassName = function () {
  42094. return "StandardMaterial";
  42095. };
  42096. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42097. get: function () {
  42098. return this._useLogarithmicDepth;
  42099. },
  42100. set: function (value) {
  42101. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42102. this._markAllSubMeshesAsMiscDirty();
  42103. },
  42104. enumerable: true,
  42105. configurable: true
  42106. });
  42107. StandardMaterial.prototype.needAlphaBlending = function () {
  42108. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42109. };
  42110. StandardMaterial.prototype.needAlphaTesting = function () {
  42111. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42112. };
  42113. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42114. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42115. };
  42116. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42117. return this._diffuseTexture;
  42118. };
  42119. /**
  42120. * Child classes can use it to update shaders
  42121. */
  42122. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42123. if (useInstances === void 0) { useInstances = false; }
  42124. if (subMesh.effect && this.isFrozen) {
  42125. if (this._wasPreviouslyReady) {
  42126. return true;
  42127. }
  42128. }
  42129. if (!subMesh._materialDefines) {
  42130. subMesh._materialDefines = new StandardMaterialDefines();
  42131. }
  42132. var scene = this.getScene();
  42133. var defines = subMesh._materialDefines;
  42134. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42135. if (defines._renderId === scene.getRenderId()) {
  42136. return true;
  42137. }
  42138. }
  42139. var engine = scene.getEngine();
  42140. // Lights
  42141. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42142. // Textures
  42143. if (defines._areTexturesDirty) {
  42144. defines._needUVs = false;
  42145. defines.MAINUV1 = false;
  42146. defines.MAINUV2 = false;
  42147. if (scene.texturesEnabled) {
  42148. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42149. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42150. return false;
  42151. }
  42152. else {
  42153. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42154. }
  42155. }
  42156. else {
  42157. defines.DIFFUSE = false;
  42158. }
  42159. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42160. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42161. return false;
  42162. }
  42163. else {
  42164. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42165. }
  42166. }
  42167. else {
  42168. defines.AMBIENT = false;
  42169. }
  42170. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42171. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42172. return false;
  42173. }
  42174. else {
  42175. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42176. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42177. }
  42178. }
  42179. else {
  42180. defines.OPACITY = false;
  42181. }
  42182. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42183. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42184. return false;
  42185. }
  42186. else {
  42187. defines._needNormals = true;
  42188. defines.REFLECTION = true;
  42189. defines.ROUGHNESS = (this._roughness > 0);
  42190. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42191. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42192. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42193. switch (this._reflectionTexture.coordinatesMode) {
  42194. case BABYLON.Texture.EXPLICIT_MODE:
  42195. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42196. break;
  42197. case BABYLON.Texture.PLANAR_MODE:
  42198. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42199. break;
  42200. case BABYLON.Texture.PROJECTION_MODE:
  42201. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42202. break;
  42203. case BABYLON.Texture.SKYBOX_MODE:
  42204. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42205. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  42206. break;
  42207. case BABYLON.Texture.SPHERICAL_MODE:
  42208. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42209. break;
  42210. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42211. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42212. break;
  42213. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42214. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42215. break;
  42216. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42217. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42218. break;
  42219. case BABYLON.Texture.CUBIC_MODE:
  42220. case BABYLON.Texture.INVCUBIC_MODE:
  42221. default:
  42222. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42223. break;
  42224. }
  42225. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42226. }
  42227. }
  42228. else {
  42229. defines.REFLECTION = false;
  42230. }
  42231. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42232. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42233. return false;
  42234. }
  42235. else {
  42236. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42237. }
  42238. }
  42239. else {
  42240. defines.EMISSIVE = false;
  42241. }
  42242. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42243. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42244. return false;
  42245. }
  42246. else {
  42247. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42248. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42249. }
  42250. }
  42251. else {
  42252. defines.LIGHTMAP = false;
  42253. }
  42254. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42255. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42256. return false;
  42257. }
  42258. else {
  42259. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42260. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42261. }
  42262. }
  42263. else {
  42264. defines.SPECULAR = false;
  42265. }
  42266. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42267. // Bump texure can not be not blocking.
  42268. if (!this._bumpTexture.isReady()) {
  42269. return false;
  42270. }
  42271. else {
  42272. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42273. defines.PARALLAX = this._useParallax;
  42274. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42275. }
  42276. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42277. }
  42278. else {
  42279. defines.BUMP = false;
  42280. }
  42281. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42282. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42283. return false;
  42284. }
  42285. else {
  42286. defines._needUVs = true;
  42287. defines.REFRACTION = true;
  42288. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42289. }
  42290. }
  42291. else {
  42292. defines.REFRACTION = false;
  42293. }
  42294. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42295. }
  42296. else {
  42297. defines.DIFFUSE = false;
  42298. defines.AMBIENT = false;
  42299. defines.OPACITY = false;
  42300. defines.REFLECTION = false;
  42301. defines.EMISSIVE = false;
  42302. defines.LIGHTMAP = false;
  42303. defines.BUMP = false;
  42304. defines.REFRACTION = false;
  42305. }
  42306. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42307. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42308. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42309. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42310. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42311. }
  42312. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42313. if (!this._imageProcessingConfiguration.isReady()) {
  42314. return false;
  42315. }
  42316. this._imageProcessingConfiguration.prepareDefines(defines);
  42317. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42318. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42319. }
  42320. if (defines._areFresnelDirty) {
  42321. if (StandardMaterial.FresnelEnabled) {
  42322. // Fresnel
  42323. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42324. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42325. this._reflectionFresnelParameters) {
  42326. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42327. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42328. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42329. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42330. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42331. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42332. defines._needNormals = true;
  42333. defines.FRESNEL = true;
  42334. }
  42335. }
  42336. else {
  42337. defines.FRESNEL = false;
  42338. }
  42339. }
  42340. // Misc.
  42341. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42342. // Attribs
  42343. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42344. // Values that need to be evaluated on every frame
  42345. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42346. // Get correct effect
  42347. if (defines.isDirty) {
  42348. defines.markAsProcessed();
  42349. scene.resetCachedMaterial();
  42350. // Fallbacks
  42351. var fallbacks = new BABYLON.EffectFallbacks();
  42352. if (defines.REFLECTION) {
  42353. fallbacks.addFallback(0, "REFLECTION");
  42354. }
  42355. if (defines.SPECULAR) {
  42356. fallbacks.addFallback(0, "SPECULAR");
  42357. }
  42358. if (defines.BUMP) {
  42359. fallbacks.addFallback(0, "BUMP");
  42360. }
  42361. if (defines.PARALLAX) {
  42362. fallbacks.addFallback(1, "PARALLAX");
  42363. }
  42364. if (defines.PARALLAXOCCLUSION) {
  42365. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42366. }
  42367. if (defines.SPECULAROVERALPHA) {
  42368. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42369. }
  42370. if (defines.FOG) {
  42371. fallbacks.addFallback(1, "FOG");
  42372. }
  42373. if (defines.POINTSIZE) {
  42374. fallbacks.addFallback(0, "POINTSIZE");
  42375. }
  42376. if (defines.LOGARITHMICDEPTH) {
  42377. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42378. }
  42379. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42380. if (defines.SPECULARTERM) {
  42381. fallbacks.addFallback(0, "SPECULARTERM");
  42382. }
  42383. if (defines.DIFFUSEFRESNEL) {
  42384. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42385. }
  42386. if (defines.OPACITYFRESNEL) {
  42387. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42388. }
  42389. if (defines.REFLECTIONFRESNEL) {
  42390. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42391. }
  42392. if (defines.EMISSIVEFRESNEL) {
  42393. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42394. }
  42395. if (defines.FRESNEL) {
  42396. fallbacks.addFallback(4, "FRESNEL");
  42397. }
  42398. //Attributes
  42399. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42400. if (defines.NORMAL) {
  42401. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42402. }
  42403. if (defines.UV1) {
  42404. attribs.push(BABYLON.VertexBuffer.UVKind);
  42405. }
  42406. if (defines.UV2) {
  42407. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42408. }
  42409. if (defines.VERTEXCOLOR) {
  42410. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42411. }
  42412. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42413. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42414. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42415. var shaderName = "default";
  42416. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42417. "vFogInfos", "vFogColor", "pointSize",
  42418. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42419. "mBones",
  42420. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42421. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42422. "vReflectionPosition", "vReflectionSize",
  42423. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42424. ];
  42425. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42426. var uniformBuffers = ["Material", "Scene"];
  42427. if (BABYLON.ImageProcessingConfiguration) {
  42428. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42429. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42430. }
  42431. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42432. uniformsNames: uniforms,
  42433. uniformBuffersNames: uniformBuffers,
  42434. samplers: samplers,
  42435. defines: defines,
  42436. maxSimultaneousLights: this._maxSimultaneousLights
  42437. });
  42438. if (this.customShaderNameResolve) {
  42439. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42440. }
  42441. var join = defines.toString();
  42442. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42443. attributes: attribs,
  42444. uniformsNames: uniforms,
  42445. uniformBuffersNames: uniformBuffers,
  42446. samplers: samplers,
  42447. defines: join,
  42448. fallbacks: fallbacks,
  42449. onCompiled: this.onCompiled,
  42450. onError: this.onError,
  42451. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42452. }, engine), defines);
  42453. this.buildUniformLayout();
  42454. }
  42455. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42456. return false;
  42457. }
  42458. defines._renderId = scene.getRenderId();
  42459. this._wasPreviouslyReady = true;
  42460. return true;
  42461. };
  42462. StandardMaterial.prototype.buildUniformLayout = function () {
  42463. // Order is important !
  42464. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42465. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42466. this._uniformBuffer.addUniform("opacityParts", 4);
  42467. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42468. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42469. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42470. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42471. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42472. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42473. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42474. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42475. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42476. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42477. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42478. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42479. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42480. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42481. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42482. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42483. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42484. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42485. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42486. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42487. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42488. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42489. this._uniformBuffer.addUniform("specularMatrix", 16);
  42490. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42491. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42492. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42493. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42494. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42495. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42496. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42497. this._uniformBuffer.addUniform("pointSize", 1);
  42498. this._uniformBuffer.create();
  42499. };
  42500. StandardMaterial.prototype.unbind = function () {
  42501. if (this._activeEffect) {
  42502. var needFlag = false;
  42503. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42504. this._activeEffect.setTexture("reflection2DSampler", null);
  42505. needFlag = true;
  42506. }
  42507. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42508. this._activeEffect.setTexture("refraction2DSampler", null);
  42509. needFlag = true;
  42510. }
  42511. if (needFlag) {
  42512. this._markAllSubMeshesAsTexturesDirty();
  42513. }
  42514. }
  42515. _super.prototype.unbind.call(this);
  42516. };
  42517. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42518. var scene = this.getScene();
  42519. var defines = subMesh._materialDefines;
  42520. if (!defines) {
  42521. return;
  42522. }
  42523. var effect = subMesh.effect;
  42524. if (!effect) {
  42525. return;
  42526. }
  42527. this._activeEffect = effect;
  42528. // Matrices
  42529. this.bindOnlyWorldMatrix(world);
  42530. // Normal Matrix
  42531. if (defines.OBJECTSPACE_NORMALMAP) {
  42532. world.toNormalMatrix(this._normalMatrix);
  42533. this.bindOnlyNormalMatrix(this._normalMatrix);
  42534. }
  42535. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42536. // Bones
  42537. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42538. if (mustRebind) {
  42539. this._uniformBuffer.bindToEffect(effect, "Material");
  42540. this.bindViewProjection(effect);
  42541. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42542. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42543. // Fresnel
  42544. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42545. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42546. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42547. }
  42548. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42549. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42550. }
  42551. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42552. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42553. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42554. }
  42555. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42556. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42557. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42558. }
  42559. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42560. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42561. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42562. }
  42563. }
  42564. // Textures
  42565. if (scene.texturesEnabled) {
  42566. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42567. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42568. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42569. if (this._diffuseTexture.hasAlpha) {
  42570. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42571. }
  42572. }
  42573. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42574. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42575. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42576. }
  42577. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42578. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42579. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42580. }
  42581. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42582. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42583. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42584. if (this._reflectionTexture.boundingBoxSize) {
  42585. var cubeTexture = this._reflectionTexture;
  42586. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42587. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42588. }
  42589. }
  42590. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42591. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42592. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42593. }
  42594. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42595. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42596. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42597. }
  42598. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42599. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42600. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42601. }
  42602. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42603. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42604. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42605. if (scene._mirroredCameraPosition) {
  42606. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42607. }
  42608. else {
  42609. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42610. }
  42611. }
  42612. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42613. var depth = 1.0;
  42614. if (!this._refractionTexture.isCube) {
  42615. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42616. if (this._refractionTexture.depth) {
  42617. depth = this._refractionTexture.depth;
  42618. }
  42619. }
  42620. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42621. }
  42622. }
  42623. // Point size
  42624. if (this.pointsCloud) {
  42625. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42626. }
  42627. if (defines.SPECULARTERM) {
  42628. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42629. }
  42630. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42631. // Diffuse
  42632. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42633. }
  42634. // Textures
  42635. if (scene.texturesEnabled) {
  42636. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42637. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42638. }
  42639. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42640. effect.setTexture("ambientSampler", this._ambientTexture);
  42641. }
  42642. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42643. effect.setTexture("opacitySampler", this._opacityTexture);
  42644. }
  42645. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42646. if (this._reflectionTexture.isCube) {
  42647. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42648. }
  42649. else {
  42650. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42651. }
  42652. }
  42653. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42654. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42655. }
  42656. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42657. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42658. }
  42659. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42660. effect.setTexture("specularSampler", this._specularTexture);
  42661. }
  42662. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42663. effect.setTexture("bumpSampler", this._bumpTexture);
  42664. }
  42665. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42666. var depth = 1.0;
  42667. if (this._refractionTexture.isCube) {
  42668. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42669. }
  42670. else {
  42671. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42672. }
  42673. }
  42674. }
  42675. // Clip plane
  42676. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42677. // Colors
  42678. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42679. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42680. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42681. }
  42682. if (mustRebind || !this.isFrozen) {
  42683. // Lights
  42684. if (scene.lightsEnabled && !this._disableLighting) {
  42685. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42686. }
  42687. // View
  42688. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42689. this.bindView(effect);
  42690. }
  42691. // Fog
  42692. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42693. // Morph targets
  42694. if (defines.NUM_MORPH_INFLUENCERS) {
  42695. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42696. }
  42697. // Log. depth
  42698. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42699. // image processing
  42700. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42701. this._imageProcessingConfiguration.bind(this._activeEffect);
  42702. }
  42703. }
  42704. this._uniformBuffer.update();
  42705. this._afterBind(mesh, this._activeEffect);
  42706. };
  42707. StandardMaterial.prototype.getAnimatables = function () {
  42708. var results = [];
  42709. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42710. results.push(this._diffuseTexture);
  42711. }
  42712. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42713. results.push(this._ambientTexture);
  42714. }
  42715. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42716. results.push(this._opacityTexture);
  42717. }
  42718. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42719. results.push(this._reflectionTexture);
  42720. }
  42721. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42722. results.push(this._emissiveTexture);
  42723. }
  42724. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42725. results.push(this._specularTexture);
  42726. }
  42727. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42728. results.push(this._bumpTexture);
  42729. }
  42730. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42731. results.push(this._lightmapTexture);
  42732. }
  42733. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42734. results.push(this._refractionTexture);
  42735. }
  42736. return results;
  42737. };
  42738. StandardMaterial.prototype.getActiveTextures = function () {
  42739. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42740. if (this._diffuseTexture) {
  42741. activeTextures.push(this._diffuseTexture);
  42742. }
  42743. if (this._ambientTexture) {
  42744. activeTextures.push(this._ambientTexture);
  42745. }
  42746. if (this._opacityTexture) {
  42747. activeTextures.push(this._opacityTexture);
  42748. }
  42749. if (this._reflectionTexture) {
  42750. activeTextures.push(this._reflectionTexture);
  42751. }
  42752. if (this._emissiveTexture) {
  42753. activeTextures.push(this._emissiveTexture);
  42754. }
  42755. if (this._specularTexture) {
  42756. activeTextures.push(this._specularTexture);
  42757. }
  42758. if (this._bumpTexture) {
  42759. activeTextures.push(this._bumpTexture);
  42760. }
  42761. if (this._lightmapTexture) {
  42762. activeTextures.push(this._lightmapTexture);
  42763. }
  42764. if (this._refractionTexture) {
  42765. activeTextures.push(this._refractionTexture);
  42766. }
  42767. return activeTextures;
  42768. };
  42769. StandardMaterial.prototype.hasTexture = function (texture) {
  42770. if (_super.prototype.hasTexture.call(this, texture)) {
  42771. return true;
  42772. }
  42773. if (this._diffuseTexture === texture) {
  42774. return true;
  42775. }
  42776. if (this._ambientTexture === texture) {
  42777. return true;
  42778. }
  42779. if (this._opacityTexture === texture) {
  42780. return true;
  42781. }
  42782. if (this._reflectionTexture === texture) {
  42783. return true;
  42784. }
  42785. if (this._emissiveTexture === texture) {
  42786. return true;
  42787. }
  42788. if (this._specularTexture === texture) {
  42789. return true;
  42790. }
  42791. if (this._bumpTexture === texture) {
  42792. return true;
  42793. }
  42794. if (this._lightmapTexture === texture) {
  42795. return true;
  42796. }
  42797. if (this._refractionTexture === texture) {
  42798. return true;
  42799. }
  42800. return false;
  42801. };
  42802. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42803. if (forceDisposeTextures) {
  42804. if (this._diffuseTexture) {
  42805. this._diffuseTexture.dispose();
  42806. }
  42807. if (this._ambientTexture) {
  42808. this._ambientTexture.dispose();
  42809. }
  42810. if (this._opacityTexture) {
  42811. this._opacityTexture.dispose();
  42812. }
  42813. if (this._reflectionTexture) {
  42814. this._reflectionTexture.dispose();
  42815. }
  42816. if (this._emissiveTexture) {
  42817. this._emissiveTexture.dispose();
  42818. }
  42819. if (this._specularTexture) {
  42820. this._specularTexture.dispose();
  42821. }
  42822. if (this._bumpTexture) {
  42823. this._bumpTexture.dispose();
  42824. }
  42825. if (this._lightmapTexture) {
  42826. this._lightmapTexture.dispose();
  42827. }
  42828. if (this._refractionTexture) {
  42829. this._refractionTexture.dispose();
  42830. }
  42831. }
  42832. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42833. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42834. }
  42835. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42836. };
  42837. StandardMaterial.prototype.clone = function (name) {
  42838. var _this = this;
  42839. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42840. result.name = name;
  42841. result.id = name;
  42842. return result;
  42843. };
  42844. StandardMaterial.prototype.serialize = function () {
  42845. return BABYLON.SerializationHelper.Serialize(this);
  42846. };
  42847. // Statics
  42848. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42849. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42850. };
  42851. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42852. get: function () {
  42853. return StandardMaterial._DiffuseTextureEnabled;
  42854. },
  42855. set: function (value) {
  42856. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42857. return;
  42858. }
  42859. StandardMaterial._DiffuseTextureEnabled = value;
  42860. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42861. },
  42862. enumerable: true,
  42863. configurable: true
  42864. });
  42865. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42866. get: function () {
  42867. return StandardMaterial._AmbientTextureEnabled;
  42868. },
  42869. set: function (value) {
  42870. if (StandardMaterial._AmbientTextureEnabled === value) {
  42871. return;
  42872. }
  42873. StandardMaterial._AmbientTextureEnabled = value;
  42874. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42875. },
  42876. enumerable: true,
  42877. configurable: true
  42878. });
  42879. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42880. get: function () {
  42881. return StandardMaterial._OpacityTextureEnabled;
  42882. },
  42883. set: function (value) {
  42884. if (StandardMaterial._OpacityTextureEnabled === value) {
  42885. return;
  42886. }
  42887. StandardMaterial._OpacityTextureEnabled = value;
  42888. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42889. },
  42890. enumerable: true,
  42891. configurable: true
  42892. });
  42893. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42894. get: function () {
  42895. return StandardMaterial._ReflectionTextureEnabled;
  42896. },
  42897. set: function (value) {
  42898. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42899. return;
  42900. }
  42901. StandardMaterial._ReflectionTextureEnabled = value;
  42902. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42903. },
  42904. enumerable: true,
  42905. configurable: true
  42906. });
  42907. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42908. get: function () {
  42909. return StandardMaterial._EmissiveTextureEnabled;
  42910. },
  42911. set: function (value) {
  42912. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42913. return;
  42914. }
  42915. StandardMaterial._EmissiveTextureEnabled = value;
  42916. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42917. },
  42918. enumerable: true,
  42919. configurable: true
  42920. });
  42921. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42922. get: function () {
  42923. return StandardMaterial._SpecularTextureEnabled;
  42924. },
  42925. set: function (value) {
  42926. if (StandardMaterial._SpecularTextureEnabled === value) {
  42927. return;
  42928. }
  42929. StandardMaterial._SpecularTextureEnabled = value;
  42930. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42931. },
  42932. enumerable: true,
  42933. configurable: true
  42934. });
  42935. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42936. get: function () {
  42937. return StandardMaterial._BumpTextureEnabled;
  42938. },
  42939. set: function (value) {
  42940. if (StandardMaterial._BumpTextureEnabled === value) {
  42941. return;
  42942. }
  42943. StandardMaterial._BumpTextureEnabled = value;
  42944. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42945. },
  42946. enumerable: true,
  42947. configurable: true
  42948. });
  42949. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42950. get: function () {
  42951. return StandardMaterial._LightmapTextureEnabled;
  42952. },
  42953. set: function (value) {
  42954. if (StandardMaterial._LightmapTextureEnabled === value) {
  42955. return;
  42956. }
  42957. StandardMaterial._LightmapTextureEnabled = value;
  42958. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42959. },
  42960. enumerable: true,
  42961. configurable: true
  42962. });
  42963. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42964. get: function () {
  42965. return StandardMaterial._RefractionTextureEnabled;
  42966. },
  42967. set: function (value) {
  42968. if (StandardMaterial._RefractionTextureEnabled === value) {
  42969. return;
  42970. }
  42971. StandardMaterial._RefractionTextureEnabled = value;
  42972. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42973. },
  42974. enumerable: true,
  42975. configurable: true
  42976. });
  42977. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42978. get: function () {
  42979. return StandardMaterial._ColorGradingTextureEnabled;
  42980. },
  42981. set: function (value) {
  42982. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42983. return;
  42984. }
  42985. StandardMaterial._ColorGradingTextureEnabled = value;
  42986. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42987. },
  42988. enumerable: true,
  42989. configurable: true
  42990. });
  42991. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42992. get: function () {
  42993. return StandardMaterial._FresnelEnabled;
  42994. },
  42995. set: function (value) {
  42996. if (StandardMaterial._FresnelEnabled === value) {
  42997. return;
  42998. }
  42999. StandardMaterial._FresnelEnabled = value;
  43000. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43001. },
  43002. enumerable: true,
  43003. configurable: true
  43004. });
  43005. // Flags used to enable or disable a type of texture for all Standard Materials
  43006. StandardMaterial._DiffuseTextureEnabled = true;
  43007. StandardMaterial._AmbientTextureEnabled = true;
  43008. StandardMaterial._OpacityTextureEnabled = true;
  43009. StandardMaterial._ReflectionTextureEnabled = true;
  43010. StandardMaterial._EmissiveTextureEnabled = true;
  43011. StandardMaterial._SpecularTextureEnabled = true;
  43012. StandardMaterial._BumpTextureEnabled = true;
  43013. StandardMaterial._LightmapTextureEnabled = true;
  43014. StandardMaterial._RefractionTextureEnabled = true;
  43015. StandardMaterial._ColorGradingTextureEnabled = true;
  43016. StandardMaterial._FresnelEnabled = true;
  43017. __decorate([
  43018. BABYLON.serializeAsTexture("diffuseTexture")
  43019. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43020. __decorate([
  43021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43022. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43023. __decorate([
  43024. BABYLON.serializeAsTexture("ambientTexture")
  43025. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43026. __decorate([
  43027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43028. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43029. __decorate([
  43030. BABYLON.serializeAsTexture("opacityTexture")
  43031. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43032. __decorate([
  43033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43034. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43035. __decorate([
  43036. BABYLON.serializeAsTexture("reflectionTexture")
  43037. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43038. __decorate([
  43039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43040. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43041. __decorate([
  43042. BABYLON.serializeAsTexture("emissiveTexture")
  43043. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43044. __decorate([
  43045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43046. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43047. __decorate([
  43048. BABYLON.serializeAsTexture("specularTexture")
  43049. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43050. __decorate([
  43051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43052. ], StandardMaterial.prototype, "specularTexture", void 0);
  43053. __decorate([
  43054. BABYLON.serializeAsTexture("bumpTexture")
  43055. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43056. __decorate([
  43057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43058. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43059. __decorate([
  43060. BABYLON.serializeAsTexture("lightmapTexture")
  43061. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43062. __decorate([
  43063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43064. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43065. __decorate([
  43066. BABYLON.serializeAsTexture("refractionTexture")
  43067. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43068. __decorate([
  43069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43070. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43071. __decorate([
  43072. BABYLON.serializeAsColor3("ambient")
  43073. ], StandardMaterial.prototype, "ambientColor", void 0);
  43074. __decorate([
  43075. BABYLON.serializeAsColor3("diffuse")
  43076. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43077. __decorate([
  43078. BABYLON.serializeAsColor3("specular")
  43079. ], StandardMaterial.prototype, "specularColor", void 0);
  43080. __decorate([
  43081. BABYLON.serializeAsColor3("emissive")
  43082. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43083. __decorate([
  43084. BABYLON.serialize()
  43085. ], StandardMaterial.prototype, "specularPower", void 0);
  43086. __decorate([
  43087. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43088. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43089. __decorate([
  43090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43091. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43092. __decorate([
  43093. BABYLON.serialize("useEmissiveAsIllumination")
  43094. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43095. __decorate([
  43096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43097. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43098. __decorate([
  43099. BABYLON.serialize("linkEmissiveWithDiffuse")
  43100. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43101. __decorate([
  43102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43103. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43104. __decorate([
  43105. BABYLON.serialize("useSpecularOverAlpha")
  43106. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43107. __decorate([
  43108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43109. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43110. __decorate([
  43111. BABYLON.serialize("useReflectionOverAlpha")
  43112. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43113. __decorate([
  43114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43115. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43116. __decorate([
  43117. BABYLON.serialize("disableLighting")
  43118. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43119. __decorate([
  43120. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43121. ], StandardMaterial.prototype, "disableLighting", void 0);
  43122. __decorate([
  43123. BABYLON.serialize("useObjectSpaceNormalMap")
  43124. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43125. __decorate([
  43126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43127. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43128. __decorate([
  43129. BABYLON.serialize("useParallax")
  43130. ], StandardMaterial.prototype, "_useParallax", void 0);
  43131. __decorate([
  43132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43133. ], StandardMaterial.prototype, "useParallax", void 0);
  43134. __decorate([
  43135. BABYLON.serialize("useParallaxOcclusion")
  43136. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43137. __decorate([
  43138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43139. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43140. __decorate([
  43141. BABYLON.serialize()
  43142. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43143. __decorate([
  43144. BABYLON.serialize("roughness")
  43145. ], StandardMaterial.prototype, "_roughness", void 0);
  43146. __decorate([
  43147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43148. ], StandardMaterial.prototype, "roughness", void 0);
  43149. __decorate([
  43150. BABYLON.serialize()
  43151. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43152. __decorate([
  43153. BABYLON.serialize()
  43154. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43155. __decorate([
  43156. BABYLON.serialize()
  43157. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43158. __decorate([
  43159. BABYLON.serialize("useLightmapAsShadowmap")
  43160. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43161. __decorate([
  43162. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43163. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43164. __decorate([
  43165. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43166. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43167. __decorate([
  43168. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43169. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43170. __decorate([
  43171. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43172. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43173. __decorate([
  43174. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43175. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43176. __decorate([
  43177. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43178. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43179. __decorate([
  43180. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43181. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43182. __decorate([
  43183. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43184. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43185. __decorate([
  43186. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43187. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43188. __decorate([
  43189. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43190. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43191. __decorate([
  43192. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43193. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43194. __decorate([
  43195. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43196. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43197. __decorate([
  43198. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43199. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43200. __decorate([
  43201. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43202. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43203. __decorate([
  43204. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43205. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43206. __decorate([
  43207. BABYLON.serialize("maxSimultaneousLights")
  43208. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43209. __decorate([
  43210. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43211. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43212. __decorate([
  43213. BABYLON.serialize("invertNormalMapX")
  43214. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43215. __decorate([
  43216. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43217. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43218. __decorate([
  43219. BABYLON.serialize("invertNormalMapY")
  43220. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43221. __decorate([
  43222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43223. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43224. __decorate([
  43225. BABYLON.serialize("twoSidedLighting")
  43226. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43227. __decorate([
  43228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43229. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43230. __decorate([
  43231. BABYLON.serialize()
  43232. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43233. return StandardMaterial;
  43234. }(BABYLON.PushMaterial));
  43235. BABYLON.StandardMaterial = StandardMaterial;
  43236. })(BABYLON || (BABYLON = {}));
  43237. //# sourceMappingURL=babylon.standardMaterial.js.map
  43238. var BABYLON;
  43239. (function (BABYLON) {
  43240. /**
  43241. * Class representing spherical polynomial coefficients to the 3rd degree
  43242. */
  43243. var SphericalPolynomial = /** @class */ (function () {
  43244. function SphericalPolynomial() {
  43245. /**
  43246. * The x coefficients of the spherical polynomial
  43247. */
  43248. this.x = BABYLON.Vector3.Zero();
  43249. /**
  43250. * The y coefficients of the spherical polynomial
  43251. */
  43252. this.y = BABYLON.Vector3.Zero();
  43253. /**
  43254. * The z coefficients of the spherical polynomial
  43255. */
  43256. this.z = BABYLON.Vector3.Zero();
  43257. /**
  43258. * The xx coefficients of the spherical polynomial
  43259. */
  43260. this.xx = BABYLON.Vector3.Zero();
  43261. /**
  43262. * The yy coefficients of the spherical polynomial
  43263. */
  43264. this.yy = BABYLON.Vector3.Zero();
  43265. /**
  43266. * The zz coefficients of the spherical polynomial
  43267. */
  43268. this.zz = BABYLON.Vector3.Zero();
  43269. /**
  43270. * The xy coefficients of the spherical polynomial
  43271. */
  43272. this.xy = BABYLON.Vector3.Zero();
  43273. /**
  43274. * The yz coefficients of the spherical polynomial
  43275. */
  43276. this.yz = BABYLON.Vector3.Zero();
  43277. /**
  43278. * The zx coefficients of the spherical polynomial
  43279. */
  43280. this.zx = BABYLON.Vector3.Zero();
  43281. }
  43282. /**
  43283. * Adds an ambient color to the spherical polynomial
  43284. * @param color the color to add
  43285. */
  43286. SphericalPolynomial.prototype.addAmbient = function (color) {
  43287. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43288. this.xx = this.xx.add(colorVector);
  43289. this.yy = this.yy.add(colorVector);
  43290. this.zz = this.zz.add(colorVector);
  43291. };
  43292. /**
  43293. * Scales the spherical polynomial by the given amount
  43294. * @param scale the amount to scale
  43295. */
  43296. SphericalPolynomial.prototype.scale = function (scale) {
  43297. this.x = this.x.scale(scale);
  43298. this.y = this.y.scale(scale);
  43299. this.z = this.z.scale(scale);
  43300. this.xx = this.xx.scale(scale);
  43301. this.yy = this.yy.scale(scale);
  43302. this.zz = this.zz.scale(scale);
  43303. this.yz = this.yz.scale(scale);
  43304. this.zx = this.zx.scale(scale);
  43305. this.xy = this.xy.scale(scale);
  43306. };
  43307. /**
  43308. * Gets the spherical polynomial from harmonics
  43309. * @param harmonics the spherical harmonics
  43310. * @returns the spherical polynomial
  43311. */
  43312. SphericalPolynomial.FromHarmonics = function (harmonics) {
  43313. var result = new SphericalPolynomial();
  43314. result.x = harmonics.l11.scale(1.02333);
  43315. result.y = harmonics.l1_1.scale(1.02333);
  43316. result.z = harmonics.l10.scale(1.02333);
  43317. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  43318. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  43319. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  43320. result.yz = harmonics.l2_1.scale(0.858086);
  43321. result.zx = harmonics.l21.scale(0.858086);
  43322. result.xy = harmonics.l2_2.scale(0.858086);
  43323. result.scale(1.0 / Math.PI);
  43324. return result;
  43325. };
  43326. /**
  43327. * Constructs a spherical polynomial from an array.
  43328. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  43329. * @returns the spherical polynomial
  43330. */
  43331. SphericalPolynomial.FromArray = function (data) {
  43332. var sp = new SphericalPolynomial();
  43333. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  43334. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  43335. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  43336. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  43337. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  43338. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  43339. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  43340. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  43341. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  43342. return sp;
  43343. };
  43344. return SphericalPolynomial;
  43345. }());
  43346. BABYLON.SphericalPolynomial = SphericalPolynomial;
  43347. /**
  43348. * Class representing spherical harmonics coefficients to the 3rd degree
  43349. */
  43350. var SphericalHarmonics = /** @class */ (function () {
  43351. function SphericalHarmonics() {
  43352. /**
  43353. * The l0,0 coefficients of the spherical harmonics
  43354. */
  43355. this.l00 = BABYLON.Vector3.Zero();
  43356. /**
  43357. * The l1,-1 coefficients of the spherical harmonics
  43358. */
  43359. this.l1_1 = BABYLON.Vector3.Zero();
  43360. /**
  43361. * The l1,0 coefficients of the spherical harmonics
  43362. */
  43363. this.l10 = BABYLON.Vector3.Zero();
  43364. /**
  43365. * The l1,1 coefficients of the spherical harmonics
  43366. */
  43367. this.l11 = BABYLON.Vector3.Zero();
  43368. /**
  43369. * The l2,-2 coefficients of the spherical harmonics
  43370. */
  43371. this.l2_2 = BABYLON.Vector3.Zero();
  43372. /**
  43373. * The l2,-1 coefficients of the spherical harmonics
  43374. */
  43375. this.l2_1 = BABYLON.Vector3.Zero();
  43376. /**
  43377. * The l2,0 coefficients of the spherical harmonics
  43378. */
  43379. this.l20 = BABYLON.Vector3.Zero();
  43380. /**
  43381. * The l2,1 coefficients of the spherical harmonics
  43382. */
  43383. this.l21 = BABYLON.Vector3.Zero();
  43384. /**
  43385. * The l2,2 coefficients of the spherical harmonics
  43386. */
  43387. this.lL22 = BABYLON.Vector3.Zero();
  43388. }
  43389. /**
  43390. * Adds a light to the spherical harmonics
  43391. * @param direction the direction of the light
  43392. * @param color the color of the light
  43393. * @param deltaSolidAngle the delta solid angle of the light
  43394. */
  43395. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43396. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43397. var c = colorVector.scale(deltaSolidAngle);
  43398. this.l00 = this.l00.add(c.scale(0.282095));
  43399. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43400. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43401. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43402. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43403. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43404. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43405. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43406. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43407. };
  43408. /**
  43409. * Scales the spherical harmonics by the given amount
  43410. * @param scale the amount to scale
  43411. */
  43412. SphericalHarmonics.prototype.scale = function (scale) {
  43413. this.l00 = this.l00.scale(scale);
  43414. this.l1_1 = this.l1_1.scale(scale);
  43415. this.l10 = this.l10.scale(scale);
  43416. this.l11 = this.l11.scale(scale);
  43417. this.l2_2 = this.l2_2.scale(scale);
  43418. this.l2_1 = this.l2_1.scale(scale);
  43419. this.l20 = this.l20.scale(scale);
  43420. this.l21 = this.l21.scale(scale);
  43421. this.lL22 = this.lL22.scale(scale);
  43422. };
  43423. /**
  43424. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43425. *
  43426. * ```
  43427. * E_lm = A_l * L_lm
  43428. * ```
  43429. *
  43430. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43431. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43432. * the scaling factors are given in equation 9.
  43433. */
  43434. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43435. // Constant (Band 0)
  43436. this.l00 = this.l00.scale(3.141593);
  43437. // Linear (Band 1)
  43438. this.l1_1 = this.l1_1.scale(2.094395);
  43439. this.l10 = this.l10.scale(2.094395);
  43440. this.l11 = this.l11.scale(2.094395);
  43441. // Quadratic (Band 2)
  43442. this.l2_2 = this.l2_2.scale(0.785398);
  43443. this.l2_1 = this.l2_1.scale(0.785398);
  43444. this.l20 = this.l20.scale(0.785398);
  43445. this.l21 = this.l21.scale(0.785398);
  43446. this.lL22 = this.lL22.scale(0.785398);
  43447. };
  43448. /**
  43449. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43450. *
  43451. * ```
  43452. * L = (1/pi) * E * rho
  43453. * ```
  43454. *
  43455. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43456. */
  43457. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43458. this.scale(1.0 / Math.PI);
  43459. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43460. // (The pixel shader must apply albedo after texture fetches, etc).
  43461. };
  43462. /**
  43463. * Gets the spherical harmonics from polynomial
  43464. * @param polynomial the spherical polynomial
  43465. * @returns the spherical harmonics
  43466. */
  43467. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43468. var result = new SphericalHarmonics();
  43469. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43470. result.l1_1 = polynomial.y.scale(0.977204);
  43471. result.l10 = polynomial.z.scale(0.977204);
  43472. result.l11 = polynomial.x.scale(0.977204);
  43473. result.l2_2 = polynomial.xy.scale(1.16538);
  43474. result.l2_1 = polynomial.yz.scale(1.16538);
  43475. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43476. result.l21 = polynomial.zx.scale(1.16538);
  43477. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43478. result.scale(Math.PI);
  43479. return result;
  43480. };
  43481. /**
  43482. * Constructs a spherical harmonics from an array.
  43483. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43484. * @returns the spherical harmonics
  43485. */
  43486. SphericalHarmonics.FromArray = function (data) {
  43487. var sh = new SphericalHarmonics();
  43488. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43489. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43490. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43491. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43492. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43493. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43494. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43495. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43496. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43497. return sh;
  43498. };
  43499. return SphericalHarmonics;
  43500. }());
  43501. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43502. })(BABYLON || (BABYLON = {}));
  43503. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43504. var BABYLON;
  43505. (function (BABYLON) {
  43506. var FileFaceOrientation = /** @class */ (function () {
  43507. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43508. this.name = name;
  43509. this.worldAxisForNormal = worldAxisForNormal;
  43510. this.worldAxisForFileX = worldAxisForFileX;
  43511. this.worldAxisForFileY = worldAxisForFileY;
  43512. }
  43513. return FileFaceOrientation;
  43514. }());
  43515. ;
  43516. /**
  43517. * Helper class dealing with the extraction of spherical polynomial dataArray
  43518. * from a cube map.
  43519. */
  43520. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43521. function CubeMapToSphericalPolynomialTools() {
  43522. }
  43523. /**
  43524. * Converts a texture to the according Spherical Polynomial data.
  43525. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43526. *
  43527. * @param texture The texture to extract the information from.
  43528. * @return The Spherical Polynomial data.
  43529. */
  43530. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43531. if (!texture.isCube) {
  43532. // Only supports cube Textures currently.
  43533. return null;
  43534. }
  43535. var size = texture.getSize().width;
  43536. var right = texture.readPixels(0);
  43537. var left = texture.readPixels(1);
  43538. var up;
  43539. var down;
  43540. if (texture.isRenderTarget) {
  43541. up = texture.readPixels(3);
  43542. down = texture.readPixels(2);
  43543. }
  43544. else {
  43545. up = texture.readPixels(2);
  43546. down = texture.readPixels(3);
  43547. }
  43548. var front = texture.readPixels(4);
  43549. var back = texture.readPixels(5);
  43550. var gammaSpace = texture.gammaSpace;
  43551. // Always read as RGBA.
  43552. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43553. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43554. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43555. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43556. }
  43557. var cubeInfo = {
  43558. size: size,
  43559. right: right,
  43560. left: left,
  43561. up: up,
  43562. down: down,
  43563. front: front,
  43564. back: back,
  43565. format: format,
  43566. type: type,
  43567. gammaSpace: gammaSpace,
  43568. };
  43569. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43570. };
  43571. /**
  43572. * Converts a cubemap to the according Spherical Polynomial data.
  43573. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43574. *
  43575. * @param cubeInfo The Cube map to extract the information from.
  43576. * @return The Spherical Polynomial data.
  43577. */
  43578. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43579. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43580. var totalSolidAngle = 0.0;
  43581. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43582. var du = 2.0 / cubeInfo.size;
  43583. var dv = du;
  43584. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43585. var minUV = du * 0.5 - 1.0;
  43586. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43587. var fileFace = this.FileFaces[faceIndex];
  43588. var dataArray = cubeInfo[fileFace.name];
  43589. var v = minUV;
  43590. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43591. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43592. // Because SP is still linear, so summation is fine in that basis.
  43593. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43594. for (var y = 0; y < cubeInfo.size; y++) {
  43595. var u = minUV;
  43596. for (var x = 0; x < cubeInfo.size; x++) {
  43597. // World direction (not normalised)
  43598. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43599. worldDirection.normalize();
  43600. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43601. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43602. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43603. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43604. // Handle Integer types.
  43605. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43606. r /= 255;
  43607. g /= 255;
  43608. b /= 255;
  43609. }
  43610. // Handle Gamma space textures.
  43611. if (cubeInfo.gammaSpace) {
  43612. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43613. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43614. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43615. }
  43616. var color = new BABYLON.Color3(r, g, b);
  43617. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43618. totalSolidAngle += deltaSolidAngle;
  43619. u += du;
  43620. }
  43621. v += dv;
  43622. }
  43623. }
  43624. // Solid angle for entire sphere is 4*pi
  43625. var sphereSolidAngle = 4.0 * Math.PI;
  43626. // Adjust the solid angle to allow for how many faces we processed.
  43627. var facesProcessed = 6.0;
  43628. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43629. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43630. // This is needed because the numerical integration over the cube uses a
  43631. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43632. // and also to compensate for accumulative error due to float precision in the summation.
  43633. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43634. sphericalHarmonics.scale(correctionFactor);
  43635. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43636. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43637. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43638. };
  43639. CubeMapToSphericalPolynomialTools.FileFaces = [
  43640. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43641. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43642. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43643. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43644. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43645. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43646. ];
  43647. return CubeMapToSphericalPolynomialTools;
  43648. }());
  43649. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43650. })(BABYLON || (BABYLON = {}));
  43651. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43652. var BABYLON;
  43653. (function (BABYLON) {
  43654. /**
  43655. * Manages the defines for the PBR Material.
  43656. * @hiddenChildren
  43657. */
  43658. var PBRMaterialDefines = /** @class */ (function (_super) {
  43659. __extends(PBRMaterialDefines, _super);
  43660. /**
  43661. * Initializes the PBR Material defines.
  43662. */
  43663. function PBRMaterialDefines() {
  43664. var _this = _super.call(this) || this;
  43665. _this.PBR = true;
  43666. _this.MAINUV1 = false;
  43667. _this.MAINUV2 = false;
  43668. _this.UV1 = false;
  43669. _this.UV2 = false;
  43670. _this.ALBEDO = false;
  43671. _this.ALBEDODIRECTUV = 0;
  43672. _this.VERTEXCOLOR = false;
  43673. _this.AMBIENT = false;
  43674. _this.AMBIENTDIRECTUV = 0;
  43675. _this.AMBIENTINGRAYSCALE = false;
  43676. _this.OPACITY = false;
  43677. _this.VERTEXALPHA = false;
  43678. _this.OPACITYDIRECTUV = 0;
  43679. _this.OPACITYRGB = false;
  43680. _this.ALPHATEST = false;
  43681. _this.DEPTHPREPASS = false;
  43682. _this.ALPHABLEND = false;
  43683. _this.ALPHAFROMALBEDO = false;
  43684. _this.ALPHATESTVALUE = "0.5";
  43685. _this.SPECULAROVERALPHA = false;
  43686. _this.RADIANCEOVERALPHA = false;
  43687. _this.ALPHAFRESNEL = false;
  43688. _this.LINEARALPHAFRESNEL = false;
  43689. _this.PREMULTIPLYALPHA = false;
  43690. _this.EMISSIVE = false;
  43691. _this.EMISSIVEDIRECTUV = 0;
  43692. _this.REFLECTIVITY = false;
  43693. _this.REFLECTIVITYDIRECTUV = 0;
  43694. _this.SPECULARTERM = false;
  43695. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43696. _this.MICROSURFACEAUTOMATIC = false;
  43697. _this.LODBASEDMICROSFURACE = false;
  43698. _this.MICROSURFACEMAP = false;
  43699. _this.MICROSURFACEMAPDIRECTUV = 0;
  43700. _this.METALLICWORKFLOW = false;
  43701. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43702. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43703. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43704. _this.AOSTOREINMETALMAPRED = false;
  43705. _this.ENVIRONMENTBRDF = false;
  43706. _this.NORMAL = false;
  43707. _this.TANGENT = false;
  43708. _this.BUMP = false;
  43709. _this.BUMPDIRECTUV = 0;
  43710. _this.OBJECTSPACE_NORMALMAP = false;
  43711. _this.PARALLAX = false;
  43712. _this.PARALLAXOCCLUSION = false;
  43713. _this.NORMALXYSCALE = true;
  43714. _this.LIGHTMAP = false;
  43715. _this.LIGHTMAPDIRECTUV = 0;
  43716. _this.USELIGHTMAPASSHADOWMAP = false;
  43717. _this.GAMMALIGHTMAP = false;
  43718. _this.REFLECTION = false;
  43719. _this.REFLECTIONMAP_3D = false;
  43720. _this.REFLECTIONMAP_SPHERICAL = false;
  43721. _this.REFLECTIONMAP_PLANAR = false;
  43722. _this.REFLECTIONMAP_CUBIC = false;
  43723. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43724. _this.REFLECTIONMAP_PROJECTION = false;
  43725. _this.REFLECTIONMAP_SKYBOX = false;
  43726. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43727. _this.REFLECTIONMAP_EXPLICIT = false;
  43728. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43729. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43730. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43731. _this.INVERTCUBICMAP = false;
  43732. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43733. _this.USESPHERICALINVERTEX = false;
  43734. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43735. _this.LODINREFLECTIONALPHA = false;
  43736. _this.GAMMAREFLECTION = false;
  43737. _this.RGBDREFLECTION = false;
  43738. _this.RADIANCEOCCLUSION = false;
  43739. _this.HORIZONOCCLUSION = false;
  43740. _this.REFRACTION = false;
  43741. _this.REFRACTIONMAP_3D = false;
  43742. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43743. _this.LODINREFRACTIONALPHA = false;
  43744. _this.GAMMAREFRACTION = false;
  43745. _this.RGBDREFRACTION = false;
  43746. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43747. _this.INSTANCES = false;
  43748. _this.NUM_BONE_INFLUENCERS = 0;
  43749. _this.BonesPerMesh = 0;
  43750. _this.NONUNIFORMSCALING = false;
  43751. _this.MORPHTARGETS = false;
  43752. _this.MORPHTARGETS_NORMAL = false;
  43753. _this.MORPHTARGETS_TANGENT = false;
  43754. _this.NUM_MORPH_INFLUENCERS = 0;
  43755. _this.IMAGEPROCESSING = false;
  43756. _this.VIGNETTE = false;
  43757. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43758. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43759. _this.TONEMAPPING = false;
  43760. _this.TONEMAPPING_ACES = false;
  43761. _this.CONTRAST = false;
  43762. _this.COLORCURVES = false;
  43763. _this.COLORGRADING = false;
  43764. _this.COLORGRADING3D = false;
  43765. _this.SAMPLER3DGREENDEPTH = false;
  43766. _this.SAMPLER3DBGRMAP = false;
  43767. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43768. _this.EXPOSURE = false;
  43769. _this.USEPHYSICALLIGHTFALLOFF = false;
  43770. _this.USEGLTFLIGHTFALLOFF = false;
  43771. _this.TWOSIDEDLIGHTING = false;
  43772. _this.SHADOWFLOAT = false;
  43773. _this.CLIPPLANE = false;
  43774. _this.CLIPPLANE2 = false;
  43775. _this.CLIPPLANE3 = false;
  43776. _this.CLIPPLANE4 = false;
  43777. _this.POINTSIZE = false;
  43778. _this.FOG = false;
  43779. _this.LOGARITHMICDEPTH = false;
  43780. _this.FORCENORMALFORWARD = false;
  43781. _this.SPECULARAA = false;
  43782. _this.UNLIT = false;
  43783. _this.rebuild();
  43784. return _this;
  43785. }
  43786. /**
  43787. * Resets the PBR Material defines.
  43788. */
  43789. PBRMaterialDefines.prototype.reset = function () {
  43790. _super.prototype.reset.call(this);
  43791. this.ALPHATESTVALUE = "0.5";
  43792. this.PBR = true;
  43793. };
  43794. return PBRMaterialDefines;
  43795. }(BABYLON.MaterialDefines));
  43796. /**
  43797. * The Physically based material base class of BJS.
  43798. *
  43799. * This offers the main features of a standard PBR material.
  43800. * For more information, please refer to the documentation :
  43801. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43802. */
  43803. var PBRBaseMaterial = /** @class */ (function (_super) {
  43804. __extends(PBRBaseMaterial, _super);
  43805. /**
  43806. * Instantiates a new PBRMaterial instance.
  43807. *
  43808. * @param name The material name
  43809. * @param scene The scene the material will be use in.
  43810. */
  43811. function PBRBaseMaterial(name, scene) {
  43812. var _this = _super.call(this, name, scene) || this;
  43813. /**
  43814. * Intensity of the direct lights e.g. the four lights available in your scene.
  43815. * This impacts both the direct diffuse and specular highlights.
  43816. */
  43817. _this._directIntensity = 1.0;
  43818. /**
  43819. * Intensity of the emissive part of the material.
  43820. * This helps controlling the emissive effect without modifying the emissive color.
  43821. */
  43822. _this._emissiveIntensity = 1.0;
  43823. /**
  43824. * Intensity of the environment e.g. how much the environment will light the object
  43825. * either through harmonics for rough material or through the refelction for shiny ones.
  43826. */
  43827. _this._environmentIntensity = 1.0;
  43828. /**
  43829. * This is a special control allowing the reduction of the specular highlights coming from the
  43830. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43831. */
  43832. _this._specularIntensity = 1.0;
  43833. /**
  43834. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43835. */
  43836. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43837. /**
  43838. * Debug Control allowing disabling the bump map on this material.
  43839. */
  43840. _this._disableBumpMap = false;
  43841. /**
  43842. * AKA Occlusion Texture Intensity in other nomenclature.
  43843. */
  43844. _this._ambientTextureStrength = 1.0;
  43845. /**
  43846. * Defines how much the AO map is occluding the analytical lights (point spot...).
  43847. * 1 means it completely occludes it
  43848. * 0 mean it has no impact
  43849. */
  43850. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  43851. /**
  43852. * The color of a material in ambient lighting.
  43853. */
  43854. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43855. /**
  43856. * AKA Diffuse Color in other nomenclature.
  43857. */
  43858. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43859. /**
  43860. * AKA Specular Color in other nomenclature.
  43861. */
  43862. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43863. /**
  43864. * The color applied when light is reflected from a material.
  43865. */
  43866. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43867. /**
  43868. * The color applied when light is emitted from a material.
  43869. */
  43870. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43871. /**
  43872. * AKA Glossiness in other nomenclature.
  43873. */
  43874. _this._microSurface = 0.9;
  43875. /**
  43876. * source material index of refraction (IOR)' / 'destination material IOR.
  43877. */
  43878. _this._indexOfRefraction = 0.66;
  43879. /**
  43880. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43881. */
  43882. _this._invertRefractionY = false;
  43883. /**
  43884. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43885. * Materials half opaque for instance using refraction could benefit from this control.
  43886. */
  43887. _this._linkRefractionWithTransparency = false;
  43888. /**
  43889. * Specifies that the material will use the light map as a show map.
  43890. */
  43891. _this._useLightmapAsShadowmap = false;
  43892. /**
  43893. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43894. * makes the reflect vector face the model (under horizon).
  43895. */
  43896. _this._useHorizonOcclusion = true;
  43897. /**
  43898. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43899. * too much the area relying on ambient texture to define their ambient occlusion.
  43900. */
  43901. _this._useRadianceOcclusion = true;
  43902. /**
  43903. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43904. */
  43905. _this._useAlphaFromAlbedoTexture = false;
  43906. /**
  43907. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43908. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43909. */
  43910. _this._useSpecularOverAlpha = true;
  43911. /**
  43912. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43913. */
  43914. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43915. /**
  43916. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43917. */
  43918. _this._useRoughnessFromMetallicTextureAlpha = true;
  43919. /**
  43920. * Specifies if the metallic texture contains the roughness information in its green channel.
  43921. */
  43922. _this._useRoughnessFromMetallicTextureGreen = false;
  43923. /**
  43924. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43925. */
  43926. _this._useMetallnessFromMetallicTextureBlue = false;
  43927. /**
  43928. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43929. */
  43930. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43931. /**
  43932. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43933. */
  43934. _this._useAmbientInGrayScale = false;
  43935. /**
  43936. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43937. * The material will try to infer what glossiness each pixel should be.
  43938. */
  43939. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43940. /**
  43941. * Defines the falloff type used in this material.
  43942. * It by default is Physical.
  43943. */
  43944. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43945. /**
  43946. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43947. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43948. */
  43949. _this._useRadianceOverAlpha = true;
  43950. /**
  43951. * Allows using an object space normal map (instead of tangent space).
  43952. */
  43953. _this._useObjectSpaceNormalMap = false;
  43954. /**
  43955. * Allows using the bump map in parallax mode.
  43956. */
  43957. _this._useParallax = false;
  43958. /**
  43959. * Allows using the bump map in parallax occlusion mode.
  43960. */
  43961. _this._useParallaxOcclusion = false;
  43962. /**
  43963. * Controls the scale bias of the parallax mode.
  43964. */
  43965. _this._parallaxScaleBias = 0.05;
  43966. /**
  43967. * If sets to true, disables all the lights affecting the material.
  43968. */
  43969. _this._disableLighting = false;
  43970. /**
  43971. * Number of Simultaneous lights allowed on the material.
  43972. */
  43973. _this._maxSimultaneousLights = 4;
  43974. /**
  43975. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43976. */
  43977. _this._invertNormalMapX = false;
  43978. /**
  43979. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43980. */
  43981. _this._invertNormalMapY = false;
  43982. /**
  43983. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43984. */
  43985. _this._twoSidedLighting = false;
  43986. /**
  43987. * Defines the alpha limits in alpha test mode.
  43988. */
  43989. _this._alphaCutOff = 0.4;
  43990. /**
  43991. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43992. */
  43993. _this._forceAlphaTest = false;
  43994. /**
  43995. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43996. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43997. */
  43998. _this._useAlphaFresnel = false;
  43999. /**
  44000. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44001. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44002. */
  44003. _this._useLinearAlphaFresnel = false;
  44004. /**
  44005. * The transparency mode of the material.
  44006. */
  44007. _this._transparencyMode = null;
  44008. /**
  44009. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44010. * from cos thetav and roughness:
  44011. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44012. */
  44013. _this._environmentBRDFTexture = null;
  44014. /**
  44015. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44016. */
  44017. _this._forceIrradianceInFragment = false;
  44018. /**
  44019. * Force normal to face away from face.
  44020. */
  44021. _this._forceNormalForward = false;
  44022. /**
  44023. * Enables specular anti aliasing in the PBR shader.
  44024. * It will both interacts on the Geometry for analytical and IBL lighting.
  44025. * It also prefilter the roughness map based on the bump values.
  44026. */
  44027. _this._enableSpecularAntiAliasing = false;
  44028. /**
  44029. * Stores the available render targets.
  44030. */
  44031. _this._renderTargets = new BABYLON.SmartArray(16);
  44032. /**
  44033. * Sets the global ambient color for the material used in lighting calculations.
  44034. */
  44035. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44036. /**
  44037. * If set to true, no lighting calculations will be applied.
  44038. */
  44039. _this._unlit = false;
  44040. // Setup the default processing configuration to the scene.
  44041. _this._attachImageProcessingConfiguration(null);
  44042. _this.getRenderTargetTextures = function () {
  44043. _this._renderTargets.reset();
  44044. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44045. _this._renderTargets.push(_this._reflectionTexture);
  44046. }
  44047. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44048. _this._renderTargets.push(_this._refractionTexture);
  44049. }
  44050. return _this._renderTargets;
  44051. };
  44052. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44053. return _this;
  44054. }
  44055. /**
  44056. * Attaches a new image processing configuration to the PBR Material.
  44057. * @param configuration
  44058. */
  44059. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44060. var _this = this;
  44061. if (configuration === this._imageProcessingConfiguration) {
  44062. return;
  44063. }
  44064. // Detaches observer.
  44065. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44066. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44067. }
  44068. // Pick the scene configuration if needed.
  44069. if (!configuration) {
  44070. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44071. }
  44072. else {
  44073. this._imageProcessingConfiguration = configuration;
  44074. }
  44075. // Attaches observer.
  44076. if (this._imageProcessingConfiguration) {
  44077. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44078. _this._markAllSubMeshesAsImageProcessingDirty();
  44079. });
  44080. }
  44081. };
  44082. /**
  44083. * Gets the name of the material class.
  44084. */
  44085. PBRBaseMaterial.prototype.getClassName = function () {
  44086. return "PBRBaseMaterial";
  44087. };
  44088. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44089. /**
  44090. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44091. */
  44092. get: function () {
  44093. return this._useLogarithmicDepth;
  44094. },
  44095. /**
  44096. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44097. */
  44098. set: function (value) {
  44099. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44100. },
  44101. enumerable: true,
  44102. configurable: true
  44103. });
  44104. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44105. /**
  44106. * Gets the current transparency mode.
  44107. */
  44108. get: function () {
  44109. return this._transparencyMode;
  44110. },
  44111. /**
  44112. * Sets the transparency mode of the material.
  44113. *
  44114. * | Value | Type | Description |
  44115. * | ----- | ----------------------------------- | ----------- |
  44116. * | 0 | OPAQUE | |
  44117. * | 1 | ALPHATEST | |
  44118. * | 2 | ALPHABLEND | |
  44119. * | 3 | ALPHATESTANDBLEND | |
  44120. *
  44121. */
  44122. set: function (value) {
  44123. if (this._transparencyMode === value) {
  44124. return;
  44125. }
  44126. this._transparencyMode = value;
  44127. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44128. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44129. },
  44130. enumerable: true,
  44131. configurable: true
  44132. });
  44133. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44134. /**
  44135. * Returns true if alpha blending should be disabled.
  44136. */
  44137. get: function () {
  44138. return (this._linkRefractionWithTransparency ||
  44139. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44140. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44141. },
  44142. enumerable: true,
  44143. configurable: true
  44144. });
  44145. /**
  44146. * Specifies whether or not this material should be rendered in alpha blend mode.
  44147. */
  44148. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44149. if (this._disableAlphaBlending) {
  44150. return false;
  44151. }
  44152. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44153. };
  44154. /**
  44155. * Specifies if the mesh will require alpha blending.
  44156. * @param mesh - BJS mesh.
  44157. */
  44158. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44159. if (this._disableAlphaBlending) {
  44160. return false;
  44161. }
  44162. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44163. };
  44164. /**
  44165. * Specifies whether or not this material should be rendered in alpha test mode.
  44166. */
  44167. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44168. if (this._forceAlphaTest) {
  44169. return true;
  44170. }
  44171. if (this._linkRefractionWithTransparency) {
  44172. return false;
  44173. }
  44174. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44175. };
  44176. /**
  44177. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44178. */
  44179. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44180. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44181. };
  44182. /**
  44183. * Gets the texture used for the alpha test.
  44184. */
  44185. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44186. return this._albedoTexture;
  44187. };
  44188. /**
  44189. * Specifies that the submesh is ready to be used.
  44190. * @param mesh - BJS mesh.
  44191. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44192. * @param useInstances - Specifies that instances should be used.
  44193. * @returns - boolean indicating that the submesh is ready or not.
  44194. */
  44195. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44196. if (subMesh.effect && this.isFrozen) {
  44197. if (this._wasPreviouslyReady) {
  44198. return true;
  44199. }
  44200. }
  44201. if (!subMesh._materialDefines) {
  44202. subMesh._materialDefines = new PBRMaterialDefines();
  44203. }
  44204. var defines = subMesh._materialDefines;
  44205. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44206. if (defines._renderId === this.getScene().getRenderId()) {
  44207. return true;
  44208. }
  44209. }
  44210. var scene = this.getScene();
  44211. var engine = scene.getEngine();
  44212. if (defines._areTexturesDirty) {
  44213. if (scene.texturesEnabled) {
  44214. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44215. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44216. return false;
  44217. }
  44218. }
  44219. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44220. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44221. return false;
  44222. }
  44223. }
  44224. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44225. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44226. return false;
  44227. }
  44228. }
  44229. var reflectionTexture = this._getReflectionTexture();
  44230. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44231. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44232. return false;
  44233. }
  44234. }
  44235. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44236. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44237. return false;
  44238. }
  44239. }
  44240. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44241. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44242. return false;
  44243. }
  44244. }
  44245. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44246. if (this._metallicTexture) {
  44247. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44248. return false;
  44249. }
  44250. }
  44251. else if (this._reflectivityTexture) {
  44252. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44253. return false;
  44254. }
  44255. }
  44256. if (this._microSurfaceTexture) {
  44257. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44258. return false;
  44259. }
  44260. }
  44261. }
  44262. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44263. // Bump texture cannot be not blocking.
  44264. if (!this._bumpTexture.isReady()) {
  44265. return false;
  44266. }
  44267. }
  44268. var refractionTexture = this._getRefractionTexture();
  44269. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44270. if (!refractionTexture.isReadyOrNotBlocking()) {
  44271. return false;
  44272. }
  44273. }
  44274. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44275. // This is blocking.
  44276. if (!this._environmentBRDFTexture.isReady()) {
  44277. return false;
  44278. }
  44279. }
  44280. }
  44281. }
  44282. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44283. if (!this._imageProcessingConfiguration.isReady()) {
  44284. return false;
  44285. }
  44286. }
  44287. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44288. mesh.createNormals(true);
  44289. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44290. }
  44291. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44292. if (effect) {
  44293. scene.resetCachedMaterial();
  44294. subMesh.setEffect(effect, defines);
  44295. this.buildUniformLayout();
  44296. }
  44297. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44298. return false;
  44299. }
  44300. defines._renderId = scene.getRenderId();
  44301. this._wasPreviouslyReady = true;
  44302. return true;
  44303. };
  44304. /**
  44305. * Specifies if the material uses metallic roughness workflow.
  44306. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44307. */
  44308. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44309. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44310. return true;
  44311. }
  44312. return false;
  44313. };
  44314. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44315. if (onCompiled === void 0) { onCompiled = null; }
  44316. if (onError === void 0) { onError = null; }
  44317. if (useInstances === void 0) { useInstances = null; }
  44318. if (useClipPlane === void 0) { useClipPlane = null; }
  44319. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44320. if (!defines.isDirty) {
  44321. return null;
  44322. }
  44323. defines.markAsProcessed();
  44324. var scene = this.getScene();
  44325. var engine = scene.getEngine();
  44326. // Fallbacks
  44327. var fallbacks = new BABYLON.EffectFallbacks();
  44328. var fallbackRank = 0;
  44329. if (defines.USESPHERICALINVERTEX) {
  44330. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44331. }
  44332. if (defines.FOG) {
  44333. fallbacks.addFallback(fallbackRank, "FOG");
  44334. }
  44335. if (defines.SPECULARAA) {
  44336. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44337. }
  44338. if (defines.POINTSIZE) {
  44339. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44340. }
  44341. if (defines.LOGARITHMICDEPTH) {
  44342. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44343. }
  44344. if (defines.PARALLAX) {
  44345. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44346. }
  44347. if (defines.PARALLAXOCCLUSION) {
  44348. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44349. }
  44350. if (defines.ENVIRONMENTBRDF) {
  44351. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44352. }
  44353. if (defines.TANGENT) {
  44354. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44355. }
  44356. if (defines.BUMP) {
  44357. fallbacks.addFallback(fallbackRank++, "BUMP");
  44358. }
  44359. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44360. if (defines.SPECULARTERM) {
  44361. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44362. }
  44363. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44364. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44365. }
  44366. if (defines.LIGHTMAP) {
  44367. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44368. }
  44369. if (defines.NORMAL) {
  44370. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44371. }
  44372. if (defines.AMBIENT) {
  44373. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44374. }
  44375. if (defines.EMISSIVE) {
  44376. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44377. }
  44378. if (defines.VERTEXCOLOR) {
  44379. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44380. }
  44381. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44382. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44383. }
  44384. if (defines.MORPHTARGETS) {
  44385. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44386. }
  44387. //Attributes
  44388. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44389. if (defines.NORMAL) {
  44390. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44391. }
  44392. if (defines.TANGENT) {
  44393. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44394. }
  44395. if (defines.UV1) {
  44396. attribs.push(BABYLON.VertexBuffer.UVKind);
  44397. }
  44398. if (defines.UV2) {
  44399. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44400. }
  44401. if (defines.VERTEXCOLOR) {
  44402. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44403. }
  44404. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44405. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44406. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44407. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44408. "vFogInfos", "vFogColor", "pointSize",
  44409. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44410. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44411. "mBones",
  44412. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44413. "vLightingIntensity",
  44414. "logarithmicDepthConstant",
  44415. "vSphericalX", "vSphericalY", "vSphericalZ",
  44416. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44417. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44418. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44419. "vTangentSpaceParams"
  44420. ];
  44421. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44422. "bumpSampler", "lightmapSampler", "opacitySampler",
  44423. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44424. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44425. "microSurfaceSampler", "environmentBrdfSampler"];
  44426. var uniformBuffers = ["Material", "Scene"];
  44427. if (BABYLON.ImageProcessingConfiguration) {
  44428. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44429. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44430. }
  44431. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44432. uniformsNames: uniforms,
  44433. uniformBuffersNames: uniformBuffers,
  44434. samplers: samplers,
  44435. defines: defines,
  44436. maxSimultaneousLights: this._maxSimultaneousLights
  44437. });
  44438. var join = defines.toString();
  44439. return engine.createEffect("pbr", {
  44440. attributes: attribs,
  44441. uniformsNames: uniforms,
  44442. uniformBuffersNames: uniformBuffers,
  44443. samplers: samplers,
  44444. defines: join,
  44445. fallbacks: fallbacks,
  44446. onCompiled: onCompiled,
  44447. onError: onError,
  44448. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44449. }, engine);
  44450. };
  44451. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44452. if (useInstances === void 0) { useInstances = null; }
  44453. if (useClipPlane === void 0) { useClipPlane = null; }
  44454. var scene = this.getScene();
  44455. var engine = scene.getEngine();
  44456. // Lights
  44457. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44458. defines._needNormals = true;
  44459. // Textures
  44460. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44461. if (defines._areTexturesDirty) {
  44462. defines._needUVs = false;
  44463. if (scene.texturesEnabled) {
  44464. if (scene.getEngine().getCaps().textureLOD) {
  44465. defines.LODBASEDMICROSFURACE = true;
  44466. }
  44467. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44468. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44469. }
  44470. else {
  44471. defines.ALBEDO = false;
  44472. }
  44473. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44474. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44475. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44476. }
  44477. else {
  44478. defines.AMBIENT = false;
  44479. }
  44480. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44481. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44482. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44483. }
  44484. else {
  44485. defines.OPACITY = false;
  44486. }
  44487. var reflectionTexture = this._getReflectionTexture();
  44488. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44489. defines.REFLECTION = true;
  44490. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44491. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44492. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44493. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44494. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44495. defines.INVERTCUBICMAP = true;
  44496. }
  44497. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44498. switch (reflectionTexture.coordinatesMode) {
  44499. case BABYLON.Texture.EXPLICIT_MODE:
  44500. defines.REFLECTIONMAP_EXPLICIT = true;
  44501. break;
  44502. case BABYLON.Texture.PLANAR_MODE:
  44503. defines.REFLECTIONMAP_PLANAR = true;
  44504. break;
  44505. case BABYLON.Texture.PROJECTION_MODE:
  44506. defines.REFLECTIONMAP_PROJECTION = true;
  44507. break;
  44508. case BABYLON.Texture.SKYBOX_MODE:
  44509. defines.REFLECTIONMAP_SKYBOX = true;
  44510. break;
  44511. case BABYLON.Texture.SPHERICAL_MODE:
  44512. defines.REFLECTIONMAP_SPHERICAL = true;
  44513. break;
  44514. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44515. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44516. break;
  44517. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44518. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44519. break;
  44520. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44521. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44522. break;
  44523. case BABYLON.Texture.CUBIC_MODE:
  44524. case BABYLON.Texture.INVCUBIC_MODE:
  44525. default:
  44526. defines.REFLECTIONMAP_CUBIC = true;
  44527. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44528. break;
  44529. }
  44530. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44531. if (reflectionTexture.sphericalPolynomial) {
  44532. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44533. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44534. defines.USESPHERICALINVERTEX = false;
  44535. }
  44536. else {
  44537. defines.USESPHERICALINVERTEX = true;
  44538. }
  44539. }
  44540. }
  44541. else {
  44542. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  44543. }
  44544. }
  44545. else {
  44546. defines.REFLECTION = false;
  44547. defines.REFLECTIONMAP_3D = false;
  44548. defines.REFLECTIONMAP_SPHERICAL = false;
  44549. defines.REFLECTIONMAP_PLANAR = false;
  44550. defines.REFLECTIONMAP_CUBIC = false;
  44551. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44552. defines.REFLECTIONMAP_PROJECTION = false;
  44553. defines.REFLECTIONMAP_SKYBOX = false;
  44554. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44555. defines.REFLECTIONMAP_EXPLICIT = false;
  44556. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44557. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44558. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44559. defines.INVERTCUBICMAP = false;
  44560. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44561. defines.USESPHERICALINVERTEX = false;
  44562. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44563. defines.LODINREFLECTIONALPHA = false;
  44564. defines.GAMMAREFLECTION = false;
  44565. defines.RGBDREFLECTION = false;
  44566. }
  44567. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44568. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44569. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44570. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44571. }
  44572. else {
  44573. defines.LIGHTMAP = false;
  44574. }
  44575. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44576. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44577. }
  44578. else {
  44579. defines.EMISSIVE = false;
  44580. }
  44581. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44582. if (this._metallicTexture) {
  44583. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44584. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44585. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44586. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44587. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44588. }
  44589. else if (this._reflectivityTexture) {
  44590. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44591. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44592. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44593. }
  44594. else {
  44595. defines.REFLECTIVITY = false;
  44596. }
  44597. if (this._microSurfaceTexture) {
  44598. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44599. }
  44600. else {
  44601. defines.MICROSURFACEMAP = false;
  44602. }
  44603. }
  44604. else {
  44605. defines.REFLECTIVITY = false;
  44606. defines.MICROSURFACEMAP = false;
  44607. }
  44608. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44609. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44610. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44611. defines.PARALLAX = true;
  44612. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44613. }
  44614. else {
  44615. defines.PARALLAX = false;
  44616. }
  44617. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44618. }
  44619. else {
  44620. defines.BUMP = false;
  44621. }
  44622. var refractionTexture = this._getRefractionTexture();
  44623. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44624. defines.REFRACTION = true;
  44625. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44626. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44627. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44628. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44629. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44630. if (this._linkRefractionWithTransparency) {
  44631. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44632. }
  44633. }
  44634. else {
  44635. defines.REFRACTION = false;
  44636. }
  44637. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44638. defines.ENVIRONMENTBRDF = true;
  44639. }
  44640. else {
  44641. defines.ENVIRONMENTBRDF = false;
  44642. }
  44643. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44644. defines.ALPHAFROMALBEDO = true;
  44645. }
  44646. else {
  44647. defines.ALPHAFROMALBEDO = false;
  44648. }
  44649. }
  44650. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44651. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44652. defines.USEPHYSICALLIGHTFALLOFF = false;
  44653. defines.USEGLTFLIGHTFALLOFF = false;
  44654. }
  44655. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44656. defines.USEPHYSICALLIGHTFALLOFF = false;
  44657. defines.USEGLTFLIGHTFALLOFF = true;
  44658. }
  44659. else {
  44660. defines.USEPHYSICALLIGHTFALLOFF = true;
  44661. defines.USEGLTFLIGHTFALLOFF = false;
  44662. }
  44663. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44664. if (!this.backFaceCulling && this._twoSidedLighting) {
  44665. defines.TWOSIDEDLIGHTING = true;
  44666. }
  44667. else {
  44668. defines.TWOSIDEDLIGHTING = false;
  44669. }
  44670. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44671. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44672. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44673. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44674. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44675. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44676. }
  44677. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44678. this._imageProcessingConfiguration.prepareDefines(defines);
  44679. }
  44680. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44681. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44682. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44683. // Misc.
  44684. if (defines._areMiscDirty) {
  44685. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44686. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44687. }
  44688. // Values that need to be evaluated on every frame
  44689. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44690. // Attribs
  44691. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44692. };
  44693. /**
  44694. * Force shader compilation
  44695. */
  44696. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44697. var _this = this;
  44698. var localOptions = __assign({ clipPlane: false }, options);
  44699. var defines = new PBRMaterialDefines();
  44700. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44701. if (effect.isReady()) {
  44702. if (onCompiled) {
  44703. onCompiled(this);
  44704. }
  44705. }
  44706. else {
  44707. effect.onCompileObservable.add(function () {
  44708. if (onCompiled) {
  44709. onCompiled(_this);
  44710. }
  44711. });
  44712. }
  44713. };
  44714. /**
  44715. * Initializes the uniform buffer layout for the shader.
  44716. */
  44717. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44718. // Order is important !
  44719. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44720. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  44721. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44722. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44723. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44724. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44725. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44726. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44727. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44728. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44729. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44730. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44731. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44732. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44733. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44734. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44735. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44736. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44737. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44738. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44739. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44740. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44741. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44742. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44743. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44744. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44745. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44746. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44747. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44748. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44749. this._uniformBuffer.addUniform("pointSize", 1);
  44750. this._uniformBuffer.create();
  44751. };
  44752. /**
  44753. * Unbinds the textures.
  44754. */
  44755. PBRBaseMaterial.prototype.unbind = function () {
  44756. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44757. this._uniformBuffer.setTexture("reflectionSampler", null);
  44758. }
  44759. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44760. this._uniformBuffer.setTexture("refractionSampler", null);
  44761. }
  44762. _super.prototype.unbind.call(this);
  44763. };
  44764. /**
  44765. * Binds the submesh data.
  44766. * @param world - The world matrix.
  44767. * @param mesh - The BJS mesh.
  44768. * @param subMesh - A submesh of the BJS mesh.
  44769. */
  44770. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44771. var scene = this.getScene();
  44772. var defines = subMesh._materialDefines;
  44773. if (!defines) {
  44774. return;
  44775. }
  44776. var effect = subMesh.effect;
  44777. if (!effect) {
  44778. return;
  44779. }
  44780. this._activeEffect = effect;
  44781. // Matrices
  44782. this.bindOnlyWorldMatrix(world);
  44783. // Normal Matrix
  44784. if (defines.OBJECTSPACE_NORMALMAP) {
  44785. world.toNormalMatrix(this._normalMatrix);
  44786. this.bindOnlyNormalMatrix(this._normalMatrix);
  44787. }
  44788. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44789. // Bones
  44790. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44791. var reflectionTexture = null;
  44792. if (mustRebind) {
  44793. this._uniformBuffer.bindToEffect(effect, "Material");
  44794. this.bindViewProjection(effect);
  44795. reflectionTexture = this._getReflectionTexture();
  44796. var refractionTexture = this._getRefractionTexture();
  44797. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44798. // Texture uniforms
  44799. if (scene.texturesEnabled) {
  44800. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44801. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44802. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44803. }
  44804. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44805. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  44806. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44807. }
  44808. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44809. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44810. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44811. }
  44812. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44813. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44814. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44815. if (reflectionTexture.boundingBoxSize) {
  44816. var cubeTexture = reflectionTexture;
  44817. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44818. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44819. }
  44820. var polynomials = reflectionTexture.sphericalPolynomial;
  44821. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44822. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44823. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44824. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44825. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44826. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44827. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44828. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44829. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44830. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44831. }
  44832. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44833. }
  44834. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44835. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44836. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44837. }
  44838. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44839. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44840. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44841. }
  44842. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44843. if (this._metallicTexture) {
  44844. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44845. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44846. }
  44847. else if (this._reflectivityTexture) {
  44848. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44849. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44850. }
  44851. if (this._microSurfaceTexture) {
  44852. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44853. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44854. }
  44855. }
  44856. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44857. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44858. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44859. if (scene._mirroredCameraPosition) {
  44860. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44861. }
  44862. else {
  44863. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44864. }
  44865. }
  44866. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44867. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44868. var depth = 1.0;
  44869. if (!refractionTexture.isCube) {
  44870. if (refractionTexture.depth) {
  44871. depth = refractionTexture.depth;
  44872. }
  44873. }
  44874. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44875. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44876. }
  44877. }
  44878. // Point size
  44879. if (this.pointsCloud) {
  44880. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44881. }
  44882. // Colors
  44883. if (defines.METALLICWORKFLOW) {
  44884. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44885. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44886. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44887. }
  44888. else {
  44889. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44890. }
  44891. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44892. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44893. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44894. // Misc
  44895. this._lightingInfos.x = this._directIntensity;
  44896. this._lightingInfos.y = this._emissiveIntensity;
  44897. this._lightingInfos.z = this._environmentIntensity;
  44898. this._lightingInfos.w = this._specularIntensity;
  44899. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44900. }
  44901. // Textures
  44902. if (scene.texturesEnabled) {
  44903. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44904. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44905. }
  44906. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44907. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44908. }
  44909. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44910. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44911. }
  44912. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44913. if (defines.LODBASEDMICROSFURACE) {
  44914. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44915. }
  44916. else {
  44917. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44918. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44919. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44920. }
  44921. }
  44922. if (defines.ENVIRONMENTBRDF) {
  44923. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44924. }
  44925. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44926. if (defines.LODBASEDMICROSFURACE) {
  44927. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44928. }
  44929. else {
  44930. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44931. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44932. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44933. }
  44934. }
  44935. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44936. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44937. }
  44938. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44939. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44940. }
  44941. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44942. if (this._metallicTexture) {
  44943. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44944. }
  44945. else if (this._reflectivityTexture) {
  44946. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44947. }
  44948. if (this._microSurfaceTexture) {
  44949. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44950. }
  44951. }
  44952. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44953. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44954. }
  44955. }
  44956. // Clip plane
  44957. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44958. // Colors
  44959. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44960. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44961. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44962. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44963. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44964. }
  44965. if (mustRebind || !this.isFrozen) {
  44966. // Lights
  44967. if (scene.lightsEnabled && !this._disableLighting) {
  44968. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44969. }
  44970. // View
  44971. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44972. this.bindView(effect);
  44973. }
  44974. // Fog
  44975. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44976. // Morph targets
  44977. if (defines.NUM_MORPH_INFLUENCERS) {
  44978. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44979. }
  44980. // image processing
  44981. this._imageProcessingConfiguration.bind(this._activeEffect);
  44982. // Log. depth
  44983. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44984. }
  44985. this._uniformBuffer.update();
  44986. this._afterBind(mesh, this._activeEffect);
  44987. };
  44988. /**
  44989. * Returns the animatable textures.
  44990. * @returns - Array of animatable textures.
  44991. */
  44992. PBRBaseMaterial.prototype.getAnimatables = function () {
  44993. var results = [];
  44994. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44995. results.push(this._albedoTexture);
  44996. }
  44997. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44998. results.push(this._ambientTexture);
  44999. }
  45000. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45001. results.push(this._opacityTexture);
  45002. }
  45003. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45004. results.push(this._reflectionTexture);
  45005. }
  45006. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45007. results.push(this._emissiveTexture);
  45008. }
  45009. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45010. results.push(this._metallicTexture);
  45011. }
  45012. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45013. results.push(this._reflectivityTexture);
  45014. }
  45015. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45016. results.push(this._bumpTexture);
  45017. }
  45018. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45019. results.push(this._lightmapTexture);
  45020. }
  45021. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45022. results.push(this._refractionTexture);
  45023. }
  45024. return results;
  45025. };
  45026. /**
  45027. * Returns the texture used for reflections.
  45028. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45029. */
  45030. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45031. if (this._reflectionTexture) {
  45032. return this._reflectionTexture;
  45033. }
  45034. return this.getScene().environmentTexture;
  45035. };
  45036. /**
  45037. * Returns the texture used for refraction or null if none is used.
  45038. * @returns - Refection texture if present. If no refraction texture and refraction
  45039. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45040. */
  45041. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45042. if (this._refractionTexture) {
  45043. return this._refractionTexture;
  45044. }
  45045. if (this._linkRefractionWithTransparency) {
  45046. return this.getScene().environmentTexture;
  45047. }
  45048. return null;
  45049. };
  45050. /**
  45051. * Disposes the resources of the material.
  45052. * @param forceDisposeEffect - Forces the disposal of effects.
  45053. * @param forceDisposeTextures - Forces the disposal of all textures.
  45054. */
  45055. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45056. if (forceDisposeTextures) {
  45057. if (this._albedoTexture) {
  45058. this._albedoTexture.dispose();
  45059. }
  45060. if (this._ambientTexture) {
  45061. this._ambientTexture.dispose();
  45062. }
  45063. if (this._opacityTexture) {
  45064. this._opacityTexture.dispose();
  45065. }
  45066. if (this._reflectionTexture) {
  45067. this._reflectionTexture.dispose();
  45068. }
  45069. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45070. this._environmentBRDFTexture.dispose();
  45071. }
  45072. if (this._emissiveTexture) {
  45073. this._emissiveTexture.dispose();
  45074. }
  45075. if (this._metallicTexture) {
  45076. this._metallicTexture.dispose();
  45077. }
  45078. if (this._reflectivityTexture) {
  45079. this._reflectivityTexture.dispose();
  45080. }
  45081. if (this._bumpTexture) {
  45082. this._bumpTexture.dispose();
  45083. }
  45084. if (this._lightmapTexture) {
  45085. this._lightmapTexture.dispose();
  45086. }
  45087. if (this._refractionTexture) {
  45088. this._refractionTexture.dispose();
  45089. }
  45090. }
  45091. this._renderTargets.dispose();
  45092. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45093. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45094. }
  45095. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45096. };
  45097. /**
  45098. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  45099. */
  45100. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  45101. /**
  45102. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  45103. * to enhance interoperability with other engines.
  45104. */
  45105. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  45106. /**
  45107. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  45108. * to enhance interoperability with other materials.
  45109. */
  45110. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  45111. /**
  45112. * Stores the reflectivity values based on metallic roughness workflow.
  45113. */
  45114. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45115. __decorate([
  45116. BABYLON.serializeAsImageProcessingConfiguration()
  45117. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45118. __decorate([
  45119. BABYLON.serialize()
  45120. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45121. __decorate([
  45122. BABYLON.serialize()
  45123. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45124. return PBRBaseMaterial;
  45125. }(BABYLON.PushMaterial));
  45126. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45127. })(BABYLON || (BABYLON = {}));
  45128. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45129. var BABYLON;
  45130. (function (BABYLON) {
  45131. /**
  45132. * The Physically based simple base material of BJS.
  45133. *
  45134. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45135. * It is used as the base class for both the specGloss and metalRough conventions.
  45136. */
  45137. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45138. __extends(PBRBaseSimpleMaterial, _super);
  45139. /**
  45140. * Instantiates a new PBRMaterial instance.
  45141. *
  45142. * @param name The material name
  45143. * @param scene The scene the material will be use in.
  45144. */
  45145. function PBRBaseSimpleMaterial(name, scene) {
  45146. var _this = _super.call(this, name, scene) || this;
  45147. /**
  45148. * Number of Simultaneous lights allowed on the material.
  45149. */
  45150. _this.maxSimultaneousLights = 4;
  45151. /**
  45152. * If sets to true, disables all the lights affecting the material.
  45153. */
  45154. _this.disableLighting = false;
  45155. /**
  45156. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45157. */
  45158. _this.invertNormalMapX = false;
  45159. /**
  45160. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45161. */
  45162. _this.invertNormalMapY = false;
  45163. /**
  45164. * Emissivie color used to self-illuminate the model.
  45165. */
  45166. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45167. /**
  45168. * Occlusion Channel Strenght.
  45169. */
  45170. _this.occlusionStrength = 1.0;
  45171. _this.useLightmapAsShadowmap = false;
  45172. _this._useAlphaFromAlbedoTexture = true;
  45173. _this._useAmbientInGrayScale = true;
  45174. return _this;
  45175. }
  45176. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45177. /**
  45178. * Gets the current double sided mode.
  45179. */
  45180. get: function () {
  45181. return this._twoSidedLighting;
  45182. },
  45183. /**
  45184. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45185. */
  45186. set: function (value) {
  45187. if (this._twoSidedLighting === value) {
  45188. return;
  45189. }
  45190. this._twoSidedLighting = value;
  45191. this.backFaceCulling = !value;
  45192. this._markAllSubMeshesAsTexturesDirty();
  45193. },
  45194. enumerable: true,
  45195. configurable: true
  45196. });
  45197. /**
  45198. * Return the active textures of the material.
  45199. */
  45200. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45201. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45202. if (this.environmentTexture) {
  45203. activeTextures.push(this.environmentTexture);
  45204. }
  45205. if (this.normalTexture) {
  45206. activeTextures.push(this.normalTexture);
  45207. }
  45208. if (this.emissiveTexture) {
  45209. activeTextures.push(this.emissiveTexture);
  45210. }
  45211. if (this.occlusionTexture) {
  45212. activeTextures.push(this.occlusionTexture);
  45213. }
  45214. if (this.lightmapTexture) {
  45215. activeTextures.push(this.lightmapTexture);
  45216. }
  45217. return activeTextures;
  45218. };
  45219. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45220. if (_super.prototype.hasTexture.call(this, texture)) {
  45221. return true;
  45222. }
  45223. if (this.lightmapTexture === texture) {
  45224. return true;
  45225. }
  45226. return false;
  45227. };
  45228. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45229. return "PBRBaseSimpleMaterial";
  45230. };
  45231. __decorate([
  45232. BABYLON.serialize(),
  45233. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45234. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45235. __decorate([
  45236. BABYLON.serialize(),
  45237. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45238. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45239. __decorate([
  45240. BABYLON.serializeAsTexture(),
  45241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45242. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45243. __decorate([
  45244. BABYLON.serialize(),
  45245. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45246. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45247. __decorate([
  45248. BABYLON.serialize(),
  45249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45250. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45251. __decorate([
  45252. BABYLON.serializeAsTexture(),
  45253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45254. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45255. __decorate([
  45256. BABYLON.serializeAsColor3("emissive"),
  45257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45258. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45259. __decorate([
  45260. BABYLON.serializeAsTexture(),
  45261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45262. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45263. __decorate([
  45264. BABYLON.serialize(),
  45265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45266. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45267. __decorate([
  45268. BABYLON.serializeAsTexture(),
  45269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45270. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45271. __decorate([
  45272. BABYLON.serialize(),
  45273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45274. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45275. __decorate([
  45276. BABYLON.serialize()
  45277. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45278. __decorate([
  45279. BABYLON.serializeAsTexture(),
  45280. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45281. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45282. __decorate([
  45283. BABYLON.serialize(),
  45284. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45285. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45286. return PBRBaseSimpleMaterial;
  45287. }(BABYLON.PBRBaseMaterial));
  45288. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45289. })(BABYLON || (BABYLON = {}));
  45290. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45291. var BABYLON;
  45292. (function (BABYLON) {
  45293. /**
  45294. * The Physically based material of BJS.
  45295. *
  45296. * This offers the main features of a standard PBR material.
  45297. * For more information, please refer to the documentation :
  45298. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45299. */
  45300. var PBRMaterial = /** @class */ (function (_super) {
  45301. __extends(PBRMaterial, _super);
  45302. /**
  45303. * Instantiates a new PBRMaterial instance.
  45304. *
  45305. * @param name The material name
  45306. * @param scene The scene the material will be use in.
  45307. */
  45308. function PBRMaterial(name, scene) {
  45309. var _this = _super.call(this, name, scene) || this;
  45310. /**
  45311. * Intensity of the direct lights e.g. the four lights available in your scene.
  45312. * This impacts both the direct diffuse and specular highlights.
  45313. */
  45314. _this.directIntensity = 1.0;
  45315. /**
  45316. * Intensity of the emissive part of the material.
  45317. * This helps controlling the emissive effect without modifying the emissive color.
  45318. */
  45319. _this.emissiveIntensity = 1.0;
  45320. /**
  45321. * Intensity of the environment e.g. how much the environment will light the object
  45322. * either through harmonics for rough material or through the refelction for shiny ones.
  45323. */
  45324. _this.environmentIntensity = 1.0;
  45325. /**
  45326. * This is a special control allowing the reduction of the specular highlights coming from the
  45327. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45328. */
  45329. _this.specularIntensity = 1.0;
  45330. /**
  45331. * Debug Control allowing disabling the bump map on this material.
  45332. */
  45333. _this.disableBumpMap = false;
  45334. /**
  45335. * AKA Occlusion Texture Intensity in other nomenclature.
  45336. */
  45337. _this.ambientTextureStrength = 1.0;
  45338. /**
  45339. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45340. * 1 means it completely occludes it
  45341. * 0 mean it has no impact
  45342. */
  45343. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45344. /**
  45345. * The color of a material in ambient lighting.
  45346. */
  45347. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45348. /**
  45349. * AKA Diffuse Color in other nomenclature.
  45350. */
  45351. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45352. /**
  45353. * AKA Specular Color in other nomenclature.
  45354. */
  45355. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45356. /**
  45357. * The color reflected from the material.
  45358. */
  45359. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45360. /**
  45361. * The color emitted from the material.
  45362. */
  45363. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45364. /**
  45365. * AKA Glossiness in other nomenclature.
  45366. */
  45367. _this.microSurface = 1.0;
  45368. /**
  45369. * source material index of refraction (IOR)' / 'destination material IOR.
  45370. */
  45371. _this.indexOfRefraction = 0.66;
  45372. /**
  45373. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45374. */
  45375. _this.invertRefractionY = false;
  45376. /**
  45377. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45378. * Materials half opaque for instance using refraction could benefit from this control.
  45379. */
  45380. _this.linkRefractionWithTransparency = false;
  45381. _this.useLightmapAsShadowmap = false;
  45382. /**
  45383. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45384. */
  45385. _this.useAlphaFromAlbedoTexture = false;
  45386. /**
  45387. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45388. */
  45389. _this.forceAlphaTest = false;
  45390. /**
  45391. * Defines the alpha limits in alpha test mode.
  45392. */
  45393. _this.alphaCutOff = 0.4;
  45394. /**
  45395. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45396. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45397. */
  45398. _this.useSpecularOverAlpha = true;
  45399. /**
  45400. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45401. */
  45402. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45403. /**
  45404. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45405. */
  45406. _this.useRoughnessFromMetallicTextureAlpha = true;
  45407. /**
  45408. * Specifies if the metallic texture contains the roughness information in its green channel.
  45409. */
  45410. _this.useRoughnessFromMetallicTextureGreen = false;
  45411. /**
  45412. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45413. */
  45414. _this.useMetallnessFromMetallicTextureBlue = false;
  45415. /**
  45416. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45417. */
  45418. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45419. /**
  45420. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45421. */
  45422. _this.useAmbientInGrayScale = false;
  45423. /**
  45424. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45425. * The material will try to infer what glossiness each pixel should be.
  45426. */
  45427. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45428. /**
  45429. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45430. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45431. */
  45432. _this.useRadianceOverAlpha = true;
  45433. /**
  45434. * Allows using an object space normal map (instead of tangent space).
  45435. */
  45436. _this.useObjectSpaceNormalMap = false;
  45437. /**
  45438. * Allows using the bump map in parallax mode.
  45439. */
  45440. _this.useParallax = false;
  45441. /**
  45442. * Allows using the bump map in parallax occlusion mode.
  45443. */
  45444. _this.useParallaxOcclusion = false;
  45445. /**
  45446. * Controls the scale bias of the parallax mode.
  45447. */
  45448. _this.parallaxScaleBias = 0.05;
  45449. /**
  45450. * If sets to true, disables all the lights affecting the material.
  45451. */
  45452. _this.disableLighting = false;
  45453. /**
  45454. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45455. */
  45456. _this.forceIrradianceInFragment = false;
  45457. /**
  45458. * Number of Simultaneous lights allowed on the material.
  45459. */
  45460. _this.maxSimultaneousLights = 4;
  45461. /**
  45462. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45463. */
  45464. _this.invertNormalMapX = false;
  45465. /**
  45466. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45467. */
  45468. _this.invertNormalMapY = false;
  45469. /**
  45470. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45471. */
  45472. _this.twoSidedLighting = false;
  45473. /**
  45474. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45475. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45476. */
  45477. _this.useAlphaFresnel = false;
  45478. /**
  45479. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45480. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45481. */
  45482. _this.useLinearAlphaFresnel = false;
  45483. /**
  45484. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45485. * And/Or occlude the blended part.
  45486. */
  45487. _this.environmentBRDFTexture = null;
  45488. /**
  45489. * Force normal to face away from face.
  45490. */
  45491. _this.forceNormalForward = false;
  45492. /**
  45493. * Enables specular anti aliasing in the PBR shader.
  45494. * It will both interacts on the Geometry for analytical and IBL lighting.
  45495. * It also prefilter the roughness map based on the bump values.
  45496. */
  45497. _this.enableSpecularAntiAliasing = false;
  45498. /**
  45499. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45500. * makes the reflect vector face the model (under horizon).
  45501. */
  45502. _this.useHorizonOcclusion = true;
  45503. /**
  45504. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45505. * too much the area relying on ambient texture to define their ambient occlusion.
  45506. */
  45507. _this.useRadianceOcclusion = true;
  45508. /**
  45509. * If set to true, no lighting calculations will be applied.
  45510. */
  45511. _this.unlit = false;
  45512. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45513. return _this;
  45514. }
  45515. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  45516. /**
  45517. * BJS is using an harcoded light falloff based on a manually sets up range.
  45518. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45519. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45520. */
  45521. get: function () {
  45522. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45523. },
  45524. /**
  45525. * BJS is using an harcoded light falloff based on a manually sets up range.
  45526. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45527. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45528. */
  45529. set: function (value) {
  45530. if (value !== this.usePhysicalLightFalloff) {
  45531. // Ensure the effect will be rebuilt.
  45532. this._markAllSubMeshesAsTexturesDirty();
  45533. if (value) {
  45534. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45535. }
  45536. else {
  45537. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45538. }
  45539. }
  45540. },
  45541. enumerable: true,
  45542. configurable: true
  45543. });
  45544. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  45545. /**
  45546. * In order to support the falloff compatibility with gltf, a special mode has been added
  45547. * to reproduce the gltf light falloff.
  45548. */
  45549. get: function () {
  45550. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45551. },
  45552. /**
  45553. * In order to support the falloff compatibility with gltf, a special mode has been added
  45554. * to reproduce the gltf light falloff.
  45555. */
  45556. set: function (value) {
  45557. if (value !== this.useGLTFLightFalloff) {
  45558. // Ensure the effect will be rebuilt.
  45559. this._markAllSubMeshesAsTexturesDirty();
  45560. if (value) {
  45561. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45562. }
  45563. else {
  45564. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45565. }
  45566. }
  45567. },
  45568. enumerable: true,
  45569. configurable: true
  45570. });
  45571. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45572. /**
  45573. * Gets the image processing configuration used either in this material.
  45574. */
  45575. get: function () {
  45576. return this._imageProcessingConfiguration;
  45577. },
  45578. /**
  45579. * Sets the Default image processing configuration used either in the this material.
  45580. *
  45581. * If sets to null, the scene one is in use.
  45582. */
  45583. set: function (value) {
  45584. this._attachImageProcessingConfiguration(value);
  45585. // Ensure the effect will be rebuilt.
  45586. this._markAllSubMeshesAsTexturesDirty();
  45587. },
  45588. enumerable: true,
  45589. configurable: true
  45590. });
  45591. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45592. /**
  45593. * Gets wether the color curves effect is enabled.
  45594. */
  45595. get: function () {
  45596. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45597. },
  45598. /**
  45599. * Sets wether the color curves effect is enabled.
  45600. */
  45601. set: function (value) {
  45602. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45603. },
  45604. enumerable: true,
  45605. configurable: true
  45606. });
  45607. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45608. /**
  45609. * Gets wether the color grading effect is enabled.
  45610. */
  45611. get: function () {
  45612. return this.imageProcessingConfiguration.colorGradingEnabled;
  45613. },
  45614. /**
  45615. * Gets wether the color grading effect is enabled.
  45616. */
  45617. set: function (value) {
  45618. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45619. },
  45620. enumerable: true,
  45621. configurable: true
  45622. });
  45623. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45624. /**
  45625. * Gets wether tonemapping is enabled or not.
  45626. */
  45627. get: function () {
  45628. return this._imageProcessingConfiguration.toneMappingEnabled;
  45629. },
  45630. /**
  45631. * Sets wether tonemapping is enabled or not
  45632. */
  45633. set: function (value) {
  45634. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45635. },
  45636. enumerable: true,
  45637. configurable: true
  45638. });
  45639. ;
  45640. ;
  45641. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45642. /**
  45643. * The camera exposure used on this material.
  45644. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45645. * This corresponds to a photographic exposure.
  45646. */
  45647. get: function () {
  45648. return this._imageProcessingConfiguration.exposure;
  45649. },
  45650. /**
  45651. * The camera exposure used on this material.
  45652. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45653. * This corresponds to a photographic exposure.
  45654. */
  45655. set: function (value) {
  45656. this._imageProcessingConfiguration.exposure = value;
  45657. },
  45658. enumerable: true,
  45659. configurable: true
  45660. });
  45661. ;
  45662. ;
  45663. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45664. /**
  45665. * Gets The camera contrast used on this material.
  45666. */
  45667. get: function () {
  45668. return this._imageProcessingConfiguration.contrast;
  45669. },
  45670. /**
  45671. * Sets The camera contrast used on this material.
  45672. */
  45673. set: function (value) {
  45674. this._imageProcessingConfiguration.contrast = value;
  45675. },
  45676. enumerable: true,
  45677. configurable: true
  45678. });
  45679. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45680. /**
  45681. * Gets the Color Grading 2D Lookup Texture.
  45682. */
  45683. get: function () {
  45684. return this._imageProcessingConfiguration.colorGradingTexture;
  45685. },
  45686. /**
  45687. * Sets the Color Grading 2D Lookup Texture.
  45688. */
  45689. set: function (value) {
  45690. this._imageProcessingConfiguration.colorGradingTexture = value;
  45691. },
  45692. enumerable: true,
  45693. configurable: true
  45694. });
  45695. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45696. /**
  45697. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45698. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45699. * 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;
  45700. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45701. */
  45702. get: function () {
  45703. return this._imageProcessingConfiguration.colorCurves;
  45704. },
  45705. /**
  45706. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45707. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45708. * 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;
  45709. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45710. */
  45711. set: function (value) {
  45712. this._imageProcessingConfiguration.colorCurves = value;
  45713. },
  45714. enumerable: true,
  45715. configurable: true
  45716. });
  45717. /**
  45718. * Returns the name of this material class.
  45719. */
  45720. PBRMaterial.prototype.getClassName = function () {
  45721. return "PBRMaterial";
  45722. };
  45723. /**
  45724. * Returns an array of the actively used textures.
  45725. * @returns - Array of BaseTextures
  45726. */
  45727. PBRMaterial.prototype.getActiveTextures = function () {
  45728. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45729. if (this._albedoTexture) {
  45730. activeTextures.push(this._albedoTexture);
  45731. }
  45732. if (this._ambientTexture) {
  45733. activeTextures.push(this._ambientTexture);
  45734. }
  45735. if (this._opacityTexture) {
  45736. activeTextures.push(this._opacityTexture);
  45737. }
  45738. if (this._reflectionTexture) {
  45739. activeTextures.push(this._reflectionTexture);
  45740. }
  45741. if (this._emissiveTexture) {
  45742. activeTextures.push(this._emissiveTexture);
  45743. }
  45744. if (this._reflectivityTexture) {
  45745. activeTextures.push(this._reflectivityTexture);
  45746. }
  45747. if (this._metallicTexture) {
  45748. activeTextures.push(this._metallicTexture);
  45749. }
  45750. if (this._microSurfaceTexture) {
  45751. activeTextures.push(this._microSurfaceTexture);
  45752. }
  45753. if (this._bumpTexture) {
  45754. activeTextures.push(this._bumpTexture);
  45755. }
  45756. if (this._lightmapTexture) {
  45757. activeTextures.push(this._lightmapTexture);
  45758. }
  45759. if (this._refractionTexture) {
  45760. activeTextures.push(this._refractionTexture);
  45761. }
  45762. return activeTextures;
  45763. };
  45764. /**
  45765. * Checks to see if a texture is used in the material.
  45766. * @param texture - Base texture to use.
  45767. * @returns - Boolean specifying if a texture is used in the material.
  45768. */
  45769. PBRMaterial.prototype.hasTexture = function (texture) {
  45770. if (_super.prototype.hasTexture.call(this, texture)) {
  45771. return true;
  45772. }
  45773. if (this._albedoTexture === texture) {
  45774. return true;
  45775. }
  45776. if (this._ambientTexture === texture) {
  45777. return true;
  45778. }
  45779. if (this._opacityTexture === texture) {
  45780. return true;
  45781. }
  45782. if (this._reflectionTexture === texture) {
  45783. return true;
  45784. }
  45785. if (this._reflectivityTexture === texture) {
  45786. return true;
  45787. }
  45788. if (this._metallicTexture === texture) {
  45789. return true;
  45790. }
  45791. if (this._microSurfaceTexture === texture) {
  45792. return true;
  45793. }
  45794. if (this._bumpTexture === texture) {
  45795. return true;
  45796. }
  45797. if (this._lightmapTexture === texture) {
  45798. return true;
  45799. }
  45800. if (this._refractionTexture === texture) {
  45801. return true;
  45802. }
  45803. return false;
  45804. };
  45805. /**
  45806. * Makes a duplicate of the current material.
  45807. * @param name - name to use for the new material.
  45808. */
  45809. PBRMaterial.prototype.clone = function (name) {
  45810. var _this = this;
  45811. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45812. clone.id = name;
  45813. clone.name = name;
  45814. return clone;
  45815. };
  45816. /**
  45817. * Serializes this PBR Material.
  45818. * @returns - An object with the serialized material.
  45819. */
  45820. PBRMaterial.prototype.serialize = function () {
  45821. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45822. serializationObject.customType = "BABYLON.PBRMaterial";
  45823. return serializationObject;
  45824. };
  45825. // Statics
  45826. /**
  45827. * Parses a PBR Material from a serialized object.
  45828. * @param source - Serialized object.
  45829. * @param scene - BJS scene instance.
  45830. * @param rootUrl - url for the scene object
  45831. * @returns - PBRMaterial
  45832. */
  45833. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45834. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45835. };
  45836. /**
  45837. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45838. */
  45839. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45840. /**
  45841. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45842. */
  45843. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45844. /**
  45845. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45846. */
  45847. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45848. /**
  45849. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45850. * They are also discarded below the alpha cutoff threshold to improve performances.
  45851. */
  45852. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45853. /**
  45854. * Defines the default value of how much AO map is occluding the analytical lights
  45855. * (point spot...).
  45856. */
  45857. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  45858. __decorate([
  45859. BABYLON.serialize(),
  45860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45861. ], PBRMaterial.prototype, "directIntensity", void 0);
  45862. __decorate([
  45863. BABYLON.serialize(),
  45864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45865. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45866. __decorate([
  45867. BABYLON.serialize(),
  45868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45869. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45870. __decorate([
  45871. BABYLON.serialize(),
  45872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45873. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45874. __decorate([
  45875. BABYLON.serialize(),
  45876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45877. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45878. __decorate([
  45879. BABYLON.serializeAsTexture(),
  45880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45881. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45882. __decorate([
  45883. BABYLON.serializeAsTexture(),
  45884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45885. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45886. __decorate([
  45887. BABYLON.serialize(),
  45888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45889. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45890. __decorate([
  45891. BABYLON.serialize(),
  45892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45893. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  45894. __decorate([
  45895. BABYLON.serializeAsTexture(),
  45896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45897. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45898. __decorate([
  45899. BABYLON.serializeAsTexture(),
  45900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45901. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45902. __decorate([
  45903. BABYLON.serializeAsTexture(),
  45904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45905. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45906. __decorate([
  45907. BABYLON.serializeAsTexture(),
  45908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45909. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45910. __decorate([
  45911. BABYLON.serializeAsTexture(),
  45912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45913. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45914. __decorate([
  45915. BABYLON.serialize(),
  45916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45917. ], PBRMaterial.prototype, "metallic", void 0);
  45918. __decorate([
  45919. BABYLON.serialize(),
  45920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45921. ], PBRMaterial.prototype, "roughness", void 0);
  45922. __decorate([
  45923. BABYLON.serializeAsTexture(),
  45924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45925. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45926. __decorate([
  45927. BABYLON.serializeAsTexture(),
  45928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45929. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45930. __decorate([
  45931. BABYLON.serializeAsTexture(),
  45932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45933. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45934. __decorate([
  45935. BABYLON.serializeAsTexture(),
  45936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45937. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45938. __decorate([
  45939. BABYLON.serializeAsColor3("ambient"),
  45940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45941. ], PBRMaterial.prototype, "ambientColor", void 0);
  45942. __decorate([
  45943. BABYLON.serializeAsColor3("albedo"),
  45944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45945. ], PBRMaterial.prototype, "albedoColor", void 0);
  45946. __decorate([
  45947. BABYLON.serializeAsColor3("reflectivity"),
  45948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45949. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45950. __decorate([
  45951. BABYLON.serializeAsColor3("reflection"),
  45952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45953. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45954. __decorate([
  45955. BABYLON.serializeAsColor3("emissive"),
  45956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45957. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45958. __decorate([
  45959. BABYLON.serialize(),
  45960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45961. ], PBRMaterial.prototype, "microSurface", void 0);
  45962. __decorate([
  45963. BABYLON.serialize(),
  45964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45965. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45966. __decorate([
  45967. BABYLON.serialize(),
  45968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45969. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45970. __decorate([
  45971. BABYLON.serialize(),
  45972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45973. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45974. __decorate([
  45975. BABYLON.serialize(),
  45976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45977. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45978. __decorate([
  45979. BABYLON.serialize(),
  45980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45981. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45982. __decorate([
  45983. BABYLON.serialize(),
  45984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45985. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45986. __decorate([
  45987. BABYLON.serialize(),
  45988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45989. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45990. __decorate([
  45991. BABYLON.serialize(),
  45992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45993. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45994. __decorate([
  45995. BABYLON.serialize(),
  45996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45997. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45998. __decorate([
  45999. BABYLON.serialize(),
  46000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46001. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46002. __decorate([
  46003. BABYLON.serialize(),
  46004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46005. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46006. __decorate([
  46007. BABYLON.serialize(),
  46008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46009. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46010. __decorate([
  46011. BABYLON.serialize(),
  46012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46013. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46014. __decorate([
  46015. BABYLON.serialize(),
  46016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46017. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46018. __decorate([
  46019. BABYLON.serialize(),
  46020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46021. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46022. __decorate([
  46023. BABYLON.serialize()
  46024. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  46025. __decorate([
  46026. BABYLON.serialize()
  46027. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  46028. __decorate([
  46029. BABYLON.serialize(),
  46030. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46031. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46032. __decorate([
  46033. BABYLON.serialize(),
  46034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46035. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46036. __decorate([
  46037. BABYLON.serialize(),
  46038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46039. ], PBRMaterial.prototype, "useParallax", void 0);
  46040. __decorate([
  46041. BABYLON.serialize(),
  46042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46043. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46044. __decorate([
  46045. BABYLON.serialize(),
  46046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46047. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46048. __decorate([
  46049. BABYLON.serialize(),
  46050. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46051. ], PBRMaterial.prototype, "disableLighting", void 0);
  46052. __decorate([
  46053. BABYLON.serialize(),
  46054. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46055. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46056. __decorate([
  46057. BABYLON.serialize(),
  46058. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46059. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46060. __decorate([
  46061. BABYLON.serialize(),
  46062. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46063. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46064. __decorate([
  46065. BABYLON.serialize(),
  46066. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46067. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46068. __decorate([
  46069. BABYLON.serialize(),
  46070. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46071. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46072. __decorate([
  46073. BABYLON.serialize(),
  46074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46075. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46076. __decorate([
  46077. BABYLON.serialize(),
  46078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46079. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46080. __decorate([
  46081. BABYLON.serializeAsTexture(),
  46082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46083. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46084. __decorate([
  46085. BABYLON.serialize(),
  46086. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46087. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46088. __decorate([
  46089. BABYLON.serialize(),
  46090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46091. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46092. __decorate([
  46093. BABYLON.serialize(),
  46094. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46095. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46096. __decorate([
  46097. BABYLON.serialize(),
  46098. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46099. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46100. __decorate([
  46101. BABYLON.serialize(),
  46102. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  46103. ], PBRMaterial.prototype, "unlit", void 0);
  46104. return PBRMaterial;
  46105. }(BABYLON.PBRBaseMaterial));
  46106. BABYLON.PBRMaterial = PBRMaterial;
  46107. })(BABYLON || (BABYLON = {}));
  46108. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46109. var BABYLON;
  46110. (function (BABYLON) {
  46111. /**
  46112. * The PBR material of BJS following the metal roughness convention.
  46113. *
  46114. * This fits to the PBR convention in the GLTF definition:
  46115. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46116. */
  46117. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46118. __extends(PBRMetallicRoughnessMaterial, _super);
  46119. /**
  46120. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46121. *
  46122. * @param name The material name
  46123. * @param scene The scene the material will be use in.
  46124. */
  46125. function PBRMetallicRoughnessMaterial(name, scene) {
  46126. var _this = _super.call(this, name, scene) || this;
  46127. _this._useRoughnessFromMetallicTextureAlpha = false;
  46128. _this._useRoughnessFromMetallicTextureGreen = true;
  46129. _this._useMetallnessFromMetallicTextureBlue = true;
  46130. _this.metallic = 1.0;
  46131. _this.roughness = 1.0;
  46132. return _this;
  46133. }
  46134. /**
  46135. * Return the currrent class name of the material.
  46136. */
  46137. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46138. return "PBRMetallicRoughnessMaterial";
  46139. };
  46140. /**
  46141. * Return the active textures of the material.
  46142. */
  46143. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46144. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46145. if (this.baseTexture) {
  46146. activeTextures.push(this.baseTexture);
  46147. }
  46148. if (this.metallicRoughnessTexture) {
  46149. activeTextures.push(this.metallicRoughnessTexture);
  46150. }
  46151. return activeTextures;
  46152. };
  46153. /**
  46154. * Checks to see if a texture is used in the material.
  46155. * @param texture - Base texture to use.
  46156. * @returns - Boolean specifying if a texture is used in the material.
  46157. */
  46158. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46159. if (_super.prototype.hasTexture.call(this, texture)) {
  46160. return true;
  46161. }
  46162. if (this.baseTexture === texture) {
  46163. return true;
  46164. }
  46165. if (this.metallicRoughnessTexture === texture) {
  46166. return true;
  46167. }
  46168. return false;
  46169. };
  46170. /**
  46171. * Makes a duplicate of the current material.
  46172. * @param name - name to use for the new material.
  46173. */
  46174. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46175. var _this = this;
  46176. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46177. clone.id = name;
  46178. clone.name = name;
  46179. return clone;
  46180. };
  46181. /**
  46182. * Serialize the material to a parsable JSON object.
  46183. */
  46184. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46185. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46186. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46187. return serializationObject;
  46188. };
  46189. /**
  46190. * Parses a JSON object correponding to the serialize function.
  46191. */
  46192. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46193. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46194. };
  46195. __decorate([
  46196. BABYLON.serializeAsColor3(),
  46197. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46198. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46199. __decorate([
  46200. BABYLON.serializeAsTexture(),
  46201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46202. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46203. __decorate([
  46204. BABYLON.serialize(),
  46205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46206. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46207. __decorate([
  46208. BABYLON.serialize(),
  46209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46210. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46211. __decorate([
  46212. BABYLON.serializeAsTexture(),
  46213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46214. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46215. return PBRMetallicRoughnessMaterial;
  46216. }(BABYLON.PBRBaseSimpleMaterial));
  46217. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46218. })(BABYLON || (BABYLON = {}));
  46219. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46220. var BABYLON;
  46221. (function (BABYLON) {
  46222. /**
  46223. * The PBR material of BJS following the specular glossiness convention.
  46224. *
  46225. * This fits to the PBR convention in the GLTF definition:
  46226. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46227. */
  46228. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46229. __extends(PBRSpecularGlossinessMaterial, _super);
  46230. /**
  46231. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46232. *
  46233. * @param name The material name
  46234. * @param scene The scene the material will be use in.
  46235. */
  46236. function PBRSpecularGlossinessMaterial(name, scene) {
  46237. var _this = _super.call(this, name, scene) || this;
  46238. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46239. return _this;
  46240. }
  46241. /**
  46242. * Return the currrent class name of the material.
  46243. */
  46244. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46245. return "PBRSpecularGlossinessMaterial";
  46246. };
  46247. /**
  46248. * Return the active textures of the material.
  46249. */
  46250. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46251. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46252. if (this.diffuseTexture) {
  46253. activeTextures.push(this.diffuseTexture);
  46254. }
  46255. if (this.specularGlossinessTexture) {
  46256. activeTextures.push(this.specularGlossinessTexture);
  46257. }
  46258. return activeTextures;
  46259. };
  46260. /**
  46261. * Checks to see if a texture is used in the material.
  46262. * @param texture - Base texture to use.
  46263. * @returns - Boolean specifying if a texture is used in the material.
  46264. */
  46265. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46266. if (_super.prototype.hasTexture.call(this, texture)) {
  46267. return true;
  46268. }
  46269. if (this.diffuseTexture === texture) {
  46270. return true;
  46271. }
  46272. if (this.specularGlossinessTexture === texture) {
  46273. return true;
  46274. }
  46275. return false;
  46276. };
  46277. /**
  46278. * Makes a duplicate of the current material.
  46279. * @param name - name to use for the new material.
  46280. */
  46281. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46282. var _this = this;
  46283. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46284. clone.id = name;
  46285. clone.name = name;
  46286. return clone;
  46287. };
  46288. /**
  46289. * Serialize the material to a parsable JSON object.
  46290. */
  46291. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46292. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46293. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46294. return serializationObject;
  46295. };
  46296. /**
  46297. * Parses a JSON object correponding to the serialize function.
  46298. */
  46299. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46300. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46301. };
  46302. __decorate([
  46303. BABYLON.serializeAsColor3("diffuse"),
  46304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46305. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46306. __decorate([
  46307. BABYLON.serializeAsTexture(),
  46308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46309. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46310. __decorate([
  46311. BABYLON.serializeAsColor3("specular"),
  46312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46313. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46314. __decorate([
  46315. BABYLON.serialize(),
  46316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46317. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46318. __decorate([
  46319. BABYLON.serializeAsTexture(),
  46320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46321. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46322. return PBRSpecularGlossinessMaterial;
  46323. }(BABYLON.PBRBaseSimpleMaterial));
  46324. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46325. })(BABYLON || (BABYLON = {}));
  46326. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46327. var BABYLON;
  46328. (function (BABYLON) {
  46329. BABYLON.CameraInputTypes = {};
  46330. var CameraInputsManager = /** @class */ (function () {
  46331. function CameraInputsManager(camera) {
  46332. this.attached = {};
  46333. this.camera = camera;
  46334. this.checkInputs = function () { };
  46335. }
  46336. /**
  46337. * Add an input method to a camera
  46338. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46339. * @param input camera input method
  46340. */
  46341. CameraInputsManager.prototype.add = function (input) {
  46342. var type = input.getSimpleName();
  46343. if (this.attached[type]) {
  46344. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46345. return;
  46346. }
  46347. this.attached[type] = input;
  46348. input.camera = this.camera;
  46349. //for checkInputs, we are dynamically creating a function
  46350. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46351. if (input.checkInputs) {
  46352. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46353. }
  46354. if (this.attachedElement) {
  46355. input.attachControl(this.attachedElement);
  46356. }
  46357. };
  46358. /**
  46359. * Remove a specific input method from a camera
  46360. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46361. * @param inputToRemove camera input method
  46362. */
  46363. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46364. for (var cam in this.attached) {
  46365. var input = this.attached[cam];
  46366. if (input === inputToRemove) {
  46367. input.detachControl(this.attachedElement);
  46368. input.camera = null;
  46369. delete this.attached[cam];
  46370. this.rebuildInputCheck();
  46371. }
  46372. }
  46373. };
  46374. CameraInputsManager.prototype.removeByType = function (inputType) {
  46375. for (var cam in this.attached) {
  46376. var input = this.attached[cam];
  46377. if (input.getClassName() === inputType) {
  46378. input.detachControl(this.attachedElement);
  46379. input.camera = null;
  46380. delete this.attached[cam];
  46381. this.rebuildInputCheck();
  46382. }
  46383. }
  46384. };
  46385. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46386. var current = this.checkInputs;
  46387. return function () {
  46388. current();
  46389. fn();
  46390. };
  46391. };
  46392. CameraInputsManager.prototype.attachInput = function (input) {
  46393. if (this.attachedElement) {
  46394. input.attachControl(this.attachedElement, this.noPreventDefault);
  46395. }
  46396. };
  46397. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46398. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46399. if (this.attachedElement) {
  46400. return;
  46401. }
  46402. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46403. this.attachedElement = element;
  46404. this.noPreventDefault = noPreventDefault;
  46405. for (var cam in this.attached) {
  46406. this.attached[cam].attachControl(element, noPreventDefault);
  46407. }
  46408. };
  46409. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46410. if (disconnect === void 0) { disconnect = false; }
  46411. if (this.attachedElement !== element) {
  46412. return;
  46413. }
  46414. for (var cam in this.attached) {
  46415. this.attached[cam].detachControl(element);
  46416. if (disconnect) {
  46417. this.attached[cam].camera = null;
  46418. }
  46419. }
  46420. this.attachedElement = null;
  46421. };
  46422. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46423. this.checkInputs = function () { };
  46424. for (var cam in this.attached) {
  46425. var input = this.attached[cam];
  46426. if (input.checkInputs) {
  46427. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46428. }
  46429. }
  46430. };
  46431. /**
  46432. * Remove all attached input methods from a camera
  46433. */
  46434. CameraInputsManager.prototype.clear = function () {
  46435. if (this.attachedElement) {
  46436. this.detachElement(this.attachedElement, true);
  46437. }
  46438. this.attached = {};
  46439. this.attachedElement = null;
  46440. this.checkInputs = function () { };
  46441. };
  46442. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46443. var inputs = {};
  46444. for (var cam in this.attached) {
  46445. var input = this.attached[cam];
  46446. var res = BABYLON.SerializationHelper.Serialize(input);
  46447. inputs[input.getClassName()] = res;
  46448. }
  46449. serializedCamera.inputsmgr = inputs;
  46450. };
  46451. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46452. var parsedInputs = parsedCamera.inputsmgr;
  46453. if (parsedInputs) {
  46454. this.clear();
  46455. for (var n in parsedInputs) {
  46456. var construct = BABYLON.CameraInputTypes[n];
  46457. if (construct) {
  46458. var parsedinput = parsedInputs[n];
  46459. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46460. this.add(input);
  46461. }
  46462. }
  46463. }
  46464. else {
  46465. //2016-03-08 this part is for managing backward compatibility
  46466. for (var n in this.attached) {
  46467. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46468. if (construct) {
  46469. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46470. this.remove(this.attached[n]);
  46471. this.add(input);
  46472. }
  46473. }
  46474. }
  46475. };
  46476. return CameraInputsManager;
  46477. }());
  46478. BABYLON.CameraInputsManager = CameraInputsManager;
  46479. })(BABYLON || (BABYLON = {}));
  46480. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46481. var BABYLON;
  46482. (function (BABYLON) {
  46483. var TargetCamera = /** @class */ (function (_super) {
  46484. __extends(TargetCamera, _super);
  46485. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46486. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46487. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46488. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46489. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46490. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46491. _this.speed = 2.0;
  46492. _this.noRotationConstraint = false;
  46493. _this.lockedTarget = null;
  46494. /** @hidden */
  46495. _this._currentTarget = BABYLON.Vector3.Zero();
  46496. /** @hidden */
  46497. _this._viewMatrix = BABYLON.Matrix.Zero();
  46498. /** @hidden */
  46499. _this._camMatrix = BABYLON.Matrix.Zero();
  46500. /** @hidden */
  46501. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46502. /** @hidden */
  46503. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46504. /** @hidden */
  46505. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46506. /** @hidden */
  46507. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46508. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46509. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46510. _this._defaultUp = BABYLON.Vector3.Up();
  46511. _this._cachedRotationZ = 0;
  46512. return _this;
  46513. }
  46514. TargetCamera.prototype.getFrontPosition = function (distance) {
  46515. this.getWorldMatrix();
  46516. var direction = this.getTarget().subtract(this.position);
  46517. direction.normalize();
  46518. direction.scaleInPlace(distance);
  46519. return this.globalPosition.add(direction);
  46520. };
  46521. /** @hidden */
  46522. TargetCamera.prototype._getLockedTargetPosition = function () {
  46523. if (!this.lockedTarget) {
  46524. return null;
  46525. }
  46526. if (this.lockedTarget.absolutePosition) {
  46527. this.lockedTarget.computeWorldMatrix();
  46528. }
  46529. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46530. };
  46531. TargetCamera.prototype.storeState = function () {
  46532. this._storedPosition = this.position.clone();
  46533. this._storedRotation = this.rotation.clone();
  46534. if (this.rotationQuaternion) {
  46535. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46536. }
  46537. return _super.prototype.storeState.call(this);
  46538. };
  46539. /**
  46540. * Restored camera state. You must call storeState() first
  46541. * @returns whether it was successful or not
  46542. * @hidden
  46543. */
  46544. TargetCamera.prototype._restoreStateValues = function () {
  46545. if (!_super.prototype._restoreStateValues.call(this)) {
  46546. return false;
  46547. }
  46548. this.position = this._storedPosition.clone();
  46549. this.rotation = this._storedRotation.clone();
  46550. if (this.rotationQuaternion) {
  46551. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46552. }
  46553. this.cameraDirection.copyFromFloats(0, 0, 0);
  46554. this.cameraRotation.copyFromFloats(0, 0);
  46555. return true;
  46556. };
  46557. // Cache
  46558. /** @hidden */
  46559. TargetCamera.prototype._initCache = function () {
  46560. _super.prototype._initCache.call(this);
  46561. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46562. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46563. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46564. };
  46565. /** @hidden */
  46566. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46567. if (!ignoreParentClass) {
  46568. _super.prototype._updateCache.call(this);
  46569. }
  46570. var lockedTargetPosition = this._getLockedTargetPosition();
  46571. if (!lockedTargetPosition) {
  46572. this._cache.lockedTarget = null;
  46573. }
  46574. else {
  46575. if (!this._cache.lockedTarget) {
  46576. this._cache.lockedTarget = lockedTargetPosition.clone();
  46577. }
  46578. else {
  46579. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46580. }
  46581. }
  46582. this._cache.rotation.copyFrom(this.rotation);
  46583. if (this.rotationQuaternion)
  46584. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46585. };
  46586. // Synchronized
  46587. /** @hidden */
  46588. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46589. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46590. return false;
  46591. }
  46592. var lockedTargetPosition = this._getLockedTargetPosition();
  46593. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46594. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46595. };
  46596. // Methods
  46597. /** @hidden */
  46598. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46599. var engine = this.getEngine();
  46600. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46601. };
  46602. // Target
  46603. /** @hidden */
  46604. TargetCamera.prototype.setTarget = function (target) {
  46605. this.upVector.normalize();
  46606. if (this.position.z === target.z) {
  46607. this.position.z += BABYLON.Epsilon;
  46608. }
  46609. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  46610. this._camMatrix.invert();
  46611. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46612. var vDir = target.subtract(this.position);
  46613. if (vDir.x >= 0.0) {
  46614. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46615. }
  46616. else {
  46617. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46618. }
  46619. this.rotation.z = 0;
  46620. if (isNaN(this.rotation.x)) {
  46621. this.rotation.x = 0;
  46622. }
  46623. if (isNaN(this.rotation.y)) {
  46624. this.rotation.y = 0;
  46625. }
  46626. if (isNaN(this.rotation.z)) {
  46627. this.rotation.z = 0;
  46628. }
  46629. if (this.rotationQuaternion) {
  46630. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46631. }
  46632. };
  46633. /**
  46634. * Return the current target position of the camera. This value is expressed in local space.
  46635. */
  46636. TargetCamera.prototype.getTarget = function () {
  46637. return this._currentTarget;
  46638. };
  46639. /** @hidden */
  46640. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46641. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46642. };
  46643. /** @hidden */
  46644. TargetCamera.prototype._updatePosition = function () {
  46645. if (this.parent) {
  46646. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46647. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46648. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46649. return;
  46650. }
  46651. this.position.addInPlace(this.cameraDirection);
  46652. };
  46653. /** @hidden */
  46654. TargetCamera.prototype._checkInputs = function () {
  46655. var needToMove = this._decideIfNeedsToMove();
  46656. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46657. // Move
  46658. if (needToMove) {
  46659. this._updatePosition();
  46660. }
  46661. // Rotate
  46662. if (needToRotate) {
  46663. this.rotation.x += this.cameraRotation.x;
  46664. this.rotation.y += this.cameraRotation.y;
  46665. //rotate, if quaternion is set and rotation was used
  46666. if (this.rotationQuaternion) {
  46667. var len = this.rotation.lengthSquared();
  46668. if (len) {
  46669. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46670. }
  46671. }
  46672. if (!this.noRotationConstraint) {
  46673. var limit = (Math.PI / 2) * 0.95;
  46674. if (this.rotation.x > limit)
  46675. this.rotation.x = limit;
  46676. if (this.rotation.x < -limit)
  46677. this.rotation.x = -limit;
  46678. }
  46679. }
  46680. // Inertia
  46681. if (needToMove) {
  46682. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46683. this.cameraDirection.x = 0;
  46684. }
  46685. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46686. this.cameraDirection.y = 0;
  46687. }
  46688. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46689. this.cameraDirection.z = 0;
  46690. }
  46691. this.cameraDirection.scaleInPlace(this.inertia);
  46692. }
  46693. if (needToRotate) {
  46694. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46695. this.cameraRotation.x = 0;
  46696. }
  46697. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46698. this.cameraRotation.y = 0;
  46699. }
  46700. this.cameraRotation.scaleInPlace(this.inertia);
  46701. }
  46702. _super.prototype._checkInputs.call(this);
  46703. };
  46704. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46705. if (this.rotationQuaternion) {
  46706. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46707. }
  46708. else {
  46709. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46710. }
  46711. };
  46712. /**
  46713. * 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)
  46714. * @returns the current camera
  46715. */
  46716. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46717. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46718. return this;
  46719. };
  46720. /** @hidden */
  46721. TargetCamera.prototype._getViewMatrix = function () {
  46722. if (this.lockedTarget) {
  46723. this.setTarget(this._getLockedTargetPosition());
  46724. }
  46725. // Compute
  46726. this._updateCameraRotationMatrix();
  46727. // Apply the changed rotation to the upVector.
  46728. if (this._cachedRotationZ != this.rotation.z) {
  46729. this._rotateUpVectorWithCameraRotationMatrix();
  46730. this._cachedRotationZ = this.rotation.z;
  46731. }
  46732. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46733. // Computing target and final matrix
  46734. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46735. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46736. return this._viewMatrix;
  46737. };
  46738. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46739. if (this.parent) {
  46740. var parentWorldMatrix = this.parent.getWorldMatrix();
  46741. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46742. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46743. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46744. this._markSyncedWithParent();
  46745. }
  46746. else {
  46747. this._globalPosition.copyFrom(position);
  46748. this._globalCurrentTarget.copyFrom(target);
  46749. this._globalCurrentUpVector.copyFrom(up);
  46750. }
  46751. if (this.getScene().useRightHandedSystem) {
  46752. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46753. }
  46754. else {
  46755. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46756. }
  46757. };
  46758. /**
  46759. * @override
  46760. * Override Camera.createRigCamera
  46761. */
  46762. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46763. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46764. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46765. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46766. if (!this.rotationQuaternion) {
  46767. this.rotationQuaternion = new BABYLON.Quaternion();
  46768. }
  46769. rigCamera._cameraRigParams = {};
  46770. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46771. }
  46772. return rigCamera;
  46773. }
  46774. return null;
  46775. };
  46776. /**
  46777. * @hidden
  46778. * @override
  46779. * Override Camera._updateRigCameras
  46780. */
  46781. TargetCamera.prototype._updateRigCameras = function () {
  46782. var camLeft = this._rigCameras[0];
  46783. var camRight = this._rigCameras[1];
  46784. switch (this.cameraRigMode) {
  46785. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46786. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46787. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46788. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46789. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46790. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46791. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46792. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46793. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46794. camLeft.setTarget(this.getTarget());
  46795. camRight.setTarget(this.getTarget());
  46796. break;
  46797. case BABYLON.Camera.RIG_MODE_VR:
  46798. if (camLeft.rotationQuaternion) {
  46799. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46800. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46801. }
  46802. else {
  46803. camLeft.rotation.copyFrom(this.rotation);
  46804. camRight.rotation.copyFrom(this.rotation);
  46805. }
  46806. camLeft.position.copyFrom(this.position);
  46807. camRight.position.copyFrom(this.position);
  46808. break;
  46809. }
  46810. _super.prototype._updateRigCameras.call(this);
  46811. };
  46812. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46813. if (!this._rigCamTransformMatrix) {
  46814. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46815. }
  46816. var target = this.getTarget();
  46817. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46818. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46819. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46820. };
  46821. TargetCamera.prototype.getClassName = function () {
  46822. return "TargetCamera";
  46823. };
  46824. __decorate([
  46825. BABYLON.serializeAsVector3()
  46826. ], TargetCamera.prototype, "rotation", void 0);
  46827. __decorate([
  46828. BABYLON.serialize()
  46829. ], TargetCamera.prototype, "speed", void 0);
  46830. __decorate([
  46831. BABYLON.serializeAsMeshReference("lockedTargetId")
  46832. ], TargetCamera.prototype, "lockedTarget", void 0);
  46833. return TargetCamera;
  46834. }(BABYLON.Camera));
  46835. BABYLON.TargetCamera = TargetCamera;
  46836. })(BABYLON || (BABYLON = {}));
  46837. //# sourceMappingURL=babylon.targetCamera.js.map
  46838. var BABYLON;
  46839. (function (BABYLON) {
  46840. var FreeCameraMouseInput = /** @class */ (function () {
  46841. function FreeCameraMouseInput(touchEnabled) {
  46842. if (touchEnabled === void 0) { touchEnabled = true; }
  46843. this.touchEnabled = touchEnabled;
  46844. this.buttons = [0, 1, 2];
  46845. this.angularSensibility = 2000.0;
  46846. this.previousPosition = null;
  46847. }
  46848. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46849. var _this = this;
  46850. var engine = this.camera.getEngine();
  46851. if (!this._pointerInput) {
  46852. this._pointerInput = function (p, s) {
  46853. var evt = p.event;
  46854. if (engine.isInVRExclusivePointerMode) {
  46855. return;
  46856. }
  46857. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46858. return;
  46859. }
  46860. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46861. return;
  46862. }
  46863. var srcElement = (evt.srcElement || evt.target);
  46864. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46865. try {
  46866. srcElement.setPointerCapture(evt.pointerId);
  46867. }
  46868. catch (e) {
  46869. //Nothing to do with the error. Execution will continue.
  46870. }
  46871. _this.previousPosition = {
  46872. x: evt.clientX,
  46873. y: evt.clientY
  46874. };
  46875. if (!noPreventDefault) {
  46876. evt.preventDefault();
  46877. element.focus();
  46878. }
  46879. }
  46880. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46881. try {
  46882. srcElement.releasePointerCapture(evt.pointerId);
  46883. }
  46884. catch (e) {
  46885. //Nothing to do with the error.
  46886. }
  46887. _this.previousPosition = null;
  46888. if (!noPreventDefault) {
  46889. evt.preventDefault();
  46890. }
  46891. }
  46892. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46893. if (!_this.previousPosition || engine.isPointerLock) {
  46894. return;
  46895. }
  46896. var offsetX = evt.clientX - _this.previousPosition.x;
  46897. if (_this.camera.getScene().useRightHandedSystem)
  46898. offsetX *= -1;
  46899. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46900. offsetX *= -1;
  46901. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46902. var offsetY = evt.clientY - _this.previousPosition.y;
  46903. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46904. _this.previousPosition = {
  46905. x: evt.clientX,
  46906. y: evt.clientY
  46907. };
  46908. if (!noPreventDefault) {
  46909. evt.preventDefault();
  46910. }
  46911. }
  46912. };
  46913. }
  46914. this._onMouseMove = function (evt) {
  46915. if (!engine.isPointerLock) {
  46916. return;
  46917. }
  46918. if (engine.isInVRExclusivePointerMode) {
  46919. return;
  46920. }
  46921. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46922. if (_this.camera.getScene().useRightHandedSystem)
  46923. offsetX *= -1;
  46924. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46925. offsetX *= -1;
  46926. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46927. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46928. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46929. _this.previousPosition = null;
  46930. if (!noPreventDefault) {
  46931. evt.preventDefault();
  46932. }
  46933. };
  46934. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46935. element.addEventListener("mousemove", this._onMouseMove, false);
  46936. };
  46937. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46938. if (this._observer && element) {
  46939. this.camera.getScene().onPointerObservable.remove(this._observer);
  46940. if (this._onMouseMove) {
  46941. element.removeEventListener("mousemove", this._onMouseMove);
  46942. }
  46943. this._observer = null;
  46944. this._onMouseMove = null;
  46945. this.previousPosition = null;
  46946. }
  46947. };
  46948. FreeCameraMouseInput.prototype.getClassName = function () {
  46949. return "FreeCameraMouseInput";
  46950. };
  46951. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46952. return "mouse";
  46953. };
  46954. __decorate([
  46955. BABYLON.serialize()
  46956. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46957. __decorate([
  46958. BABYLON.serialize()
  46959. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46960. return FreeCameraMouseInput;
  46961. }());
  46962. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46963. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46964. })(BABYLON || (BABYLON = {}));
  46965. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46966. var BABYLON;
  46967. (function (BABYLON) {
  46968. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46969. function FreeCameraKeyboardMoveInput() {
  46970. this._keys = new Array();
  46971. this.keysUp = [38];
  46972. this.keysDown = [40];
  46973. this.keysLeft = [37];
  46974. this.keysRight = [39];
  46975. }
  46976. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46977. var _this = this;
  46978. if (this._onCanvasBlurObserver) {
  46979. return;
  46980. }
  46981. this._scene = this.camera.getScene();
  46982. this._engine = this._scene.getEngine();
  46983. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46984. _this._keys = [];
  46985. });
  46986. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46987. var evt = info.event;
  46988. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46989. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46990. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46991. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46992. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46993. var index = _this._keys.indexOf(evt.keyCode);
  46994. if (index === -1) {
  46995. _this._keys.push(evt.keyCode);
  46996. }
  46997. if (!noPreventDefault) {
  46998. evt.preventDefault();
  46999. }
  47000. }
  47001. }
  47002. else {
  47003. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47004. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47005. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47006. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47007. var index = _this._keys.indexOf(evt.keyCode);
  47008. if (index >= 0) {
  47009. _this._keys.splice(index, 1);
  47010. }
  47011. if (!noPreventDefault) {
  47012. evt.preventDefault();
  47013. }
  47014. }
  47015. }
  47016. });
  47017. };
  47018. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47019. if (this._scene) {
  47020. if (this._onKeyboardObserver) {
  47021. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47022. }
  47023. if (this._onCanvasBlurObserver) {
  47024. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47025. }
  47026. this._onKeyboardObserver = null;
  47027. this._onCanvasBlurObserver = null;
  47028. }
  47029. this._keys = [];
  47030. };
  47031. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47032. if (this._onKeyboardObserver) {
  47033. var camera = this.camera;
  47034. // Keyboard
  47035. for (var index = 0; index < this._keys.length; index++) {
  47036. var keyCode = this._keys[index];
  47037. var speed = camera._computeLocalCameraSpeed();
  47038. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47039. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47040. }
  47041. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47042. camera._localDirection.copyFromFloats(0, 0, speed);
  47043. }
  47044. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47045. camera._localDirection.copyFromFloats(speed, 0, 0);
  47046. }
  47047. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47048. camera._localDirection.copyFromFloats(0, 0, -speed);
  47049. }
  47050. if (camera.getScene().useRightHandedSystem) {
  47051. camera._localDirection.z *= -1;
  47052. }
  47053. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47054. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47055. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47056. }
  47057. }
  47058. };
  47059. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47060. return "FreeCameraKeyboardMoveInput";
  47061. };
  47062. /** @hidden */
  47063. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47064. this._keys = [];
  47065. };
  47066. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47067. return "keyboard";
  47068. };
  47069. __decorate([
  47070. BABYLON.serialize()
  47071. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47072. __decorate([
  47073. BABYLON.serialize()
  47074. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47075. __decorate([
  47076. BABYLON.serialize()
  47077. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47078. __decorate([
  47079. BABYLON.serialize()
  47080. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47081. return FreeCameraKeyboardMoveInput;
  47082. }());
  47083. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47084. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47085. })(BABYLON || (BABYLON = {}));
  47086. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47087. var BABYLON;
  47088. (function (BABYLON) {
  47089. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47090. __extends(FreeCameraInputsManager, _super);
  47091. function FreeCameraInputsManager(camera) {
  47092. return _super.call(this, camera) || this;
  47093. }
  47094. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47095. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47096. return this;
  47097. };
  47098. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47099. if (touchEnabled === void 0) { touchEnabled = true; }
  47100. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47101. return this;
  47102. };
  47103. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47104. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47105. return this;
  47106. };
  47107. FreeCameraInputsManager.prototype.addTouch = function () {
  47108. this.add(new BABYLON.FreeCameraTouchInput());
  47109. return this;
  47110. };
  47111. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47112. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47113. return this;
  47114. };
  47115. return FreeCameraInputsManager;
  47116. }(BABYLON.CameraInputsManager));
  47117. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47118. })(BABYLON || (BABYLON = {}));
  47119. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47120. var BABYLON;
  47121. (function (BABYLON) {
  47122. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  47123. // Forcing to use the Universal camera
  47124. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  47125. });
  47126. var FreeCamera = /** @class */ (function (_super) {
  47127. __extends(FreeCamera, _super);
  47128. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47129. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47130. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47131. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47132. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47133. _this.checkCollisions = false;
  47134. _this.applyGravity = false;
  47135. _this._needMoveForGravity = false;
  47136. _this._oldPosition = BABYLON.Vector3.Zero();
  47137. _this._diffPosition = BABYLON.Vector3.Zero();
  47138. _this._newPosition = BABYLON.Vector3.Zero();
  47139. // Collisions
  47140. _this._collisionMask = -1;
  47141. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47142. if (collidedMesh === void 0) { collidedMesh = null; }
  47143. //TODO move this to the collision coordinator!
  47144. if (_this.getScene().workerCollisions)
  47145. newPosition.multiplyInPlace(_this._collider._radius);
  47146. var updatePosition = function (newPos) {
  47147. _this._newPosition.copyFrom(newPos);
  47148. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47149. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47150. _this.position.addInPlace(_this._diffPosition);
  47151. if (_this.onCollide && collidedMesh) {
  47152. _this.onCollide(collidedMesh);
  47153. }
  47154. }
  47155. };
  47156. updatePosition(newPosition);
  47157. };
  47158. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47159. _this.inputs.addKeyboard().addMouse();
  47160. return _this;
  47161. }
  47162. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47163. //-- begin properties for backward compatibility for inputs
  47164. /**
  47165. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47166. * Higher values reduce sensitivity.
  47167. */
  47168. get: function () {
  47169. var mouse = this.inputs.attached["mouse"];
  47170. if (mouse)
  47171. return mouse.angularSensibility;
  47172. return 0;
  47173. },
  47174. /**
  47175. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47176. * Higher values reduce sensitivity.
  47177. */
  47178. set: function (value) {
  47179. var mouse = this.inputs.attached["mouse"];
  47180. if (mouse)
  47181. mouse.angularSensibility = value;
  47182. },
  47183. enumerable: true,
  47184. configurable: true
  47185. });
  47186. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47187. get: function () {
  47188. var keyboard = this.inputs.attached["keyboard"];
  47189. if (keyboard)
  47190. return keyboard.keysUp;
  47191. return [];
  47192. },
  47193. set: function (value) {
  47194. var keyboard = this.inputs.attached["keyboard"];
  47195. if (keyboard)
  47196. keyboard.keysUp = value;
  47197. },
  47198. enumerable: true,
  47199. configurable: true
  47200. });
  47201. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47202. get: function () {
  47203. var keyboard = this.inputs.attached["keyboard"];
  47204. if (keyboard)
  47205. return keyboard.keysDown;
  47206. return [];
  47207. },
  47208. set: function (value) {
  47209. var keyboard = this.inputs.attached["keyboard"];
  47210. if (keyboard)
  47211. keyboard.keysDown = value;
  47212. },
  47213. enumerable: true,
  47214. configurable: true
  47215. });
  47216. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47217. get: function () {
  47218. var keyboard = this.inputs.attached["keyboard"];
  47219. if (keyboard)
  47220. return keyboard.keysLeft;
  47221. return [];
  47222. },
  47223. set: function (value) {
  47224. var keyboard = this.inputs.attached["keyboard"];
  47225. if (keyboard)
  47226. keyboard.keysLeft = value;
  47227. },
  47228. enumerable: true,
  47229. configurable: true
  47230. });
  47231. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47232. get: function () {
  47233. var keyboard = this.inputs.attached["keyboard"];
  47234. if (keyboard)
  47235. return keyboard.keysRight;
  47236. return [];
  47237. },
  47238. set: function (value) {
  47239. var keyboard = this.inputs.attached["keyboard"];
  47240. if (keyboard)
  47241. keyboard.keysRight = value;
  47242. },
  47243. enumerable: true,
  47244. configurable: true
  47245. });
  47246. // Controls
  47247. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47248. this.inputs.attachElement(element, noPreventDefault);
  47249. };
  47250. FreeCamera.prototype.detachControl = function (element) {
  47251. this.inputs.detachElement(element);
  47252. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47253. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47254. };
  47255. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47256. get: function () {
  47257. return this._collisionMask;
  47258. },
  47259. set: function (mask) {
  47260. this._collisionMask = !isNaN(mask) ? mask : -1;
  47261. },
  47262. enumerable: true,
  47263. configurable: true
  47264. });
  47265. /** @hidden */
  47266. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47267. var globalPosition;
  47268. if (this.parent) {
  47269. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47270. }
  47271. else {
  47272. globalPosition = this.position;
  47273. }
  47274. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47275. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47276. if (!this._collider) {
  47277. this._collider = new BABYLON.Collider();
  47278. }
  47279. this._collider._radius = this.ellipsoid;
  47280. this._collider.collisionMask = this._collisionMask;
  47281. //no need for clone, as long as gravity is not on.
  47282. var actualDisplacement = displacement;
  47283. //add gravity to the direction to prevent the dual-collision checking
  47284. if (this.applyGravity) {
  47285. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47286. actualDisplacement = displacement.add(this.getScene().gravity);
  47287. }
  47288. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47289. };
  47290. /** @hidden */
  47291. FreeCamera.prototype._checkInputs = function () {
  47292. if (!this._localDirection) {
  47293. this._localDirection = BABYLON.Vector3.Zero();
  47294. this._transformedDirection = BABYLON.Vector3.Zero();
  47295. }
  47296. this.inputs.checkInputs();
  47297. _super.prototype._checkInputs.call(this);
  47298. };
  47299. /** @hidden */
  47300. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47301. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47302. };
  47303. /** @hidden */
  47304. FreeCamera.prototype._updatePosition = function () {
  47305. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47306. this._collideWithWorld(this.cameraDirection);
  47307. }
  47308. else {
  47309. _super.prototype._updatePosition.call(this);
  47310. }
  47311. };
  47312. FreeCamera.prototype.dispose = function () {
  47313. this.inputs.clear();
  47314. _super.prototype.dispose.call(this);
  47315. };
  47316. FreeCamera.prototype.getClassName = function () {
  47317. return "FreeCamera";
  47318. };
  47319. __decorate([
  47320. BABYLON.serializeAsVector3()
  47321. ], FreeCamera.prototype, "ellipsoid", void 0);
  47322. __decorate([
  47323. BABYLON.serializeAsVector3()
  47324. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47325. __decorate([
  47326. BABYLON.serialize()
  47327. ], FreeCamera.prototype, "checkCollisions", void 0);
  47328. __decorate([
  47329. BABYLON.serialize()
  47330. ], FreeCamera.prototype, "applyGravity", void 0);
  47331. return FreeCamera;
  47332. }(BABYLON.TargetCamera));
  47333. BABYLON.FreeCamera = FreeCamera;
  47334. })(BABYLON || (BABYLON = {}));
  47335. //# sourceMappingURL=babylon.freeCamera.js.map
  47336. var BABYLON;
  47337. (function (BABYLON) {
  47338. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47339. function ArcRotateCameraKeyboardMoveInput() {
  47340. this._keys = new Array();
  47341. this.keysUp = [38];
  47342. this.keysDown = [40];
  47343. this.keysLeft = [37];
  47344. this.keysRight = [39];
  47345. this.keysReset = [220];
  47346. this.panningSensibility = 50.0;
  47347. this.zoomingSensibility = 25.0;
  47348. this.useAltToZoom = true;
  47349. }
  47350. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47351. var _this = this;
  47352. if (this._onCanvasBlurObserver) {
  47353. return;
  47354. }
  47355. this._scene = this.camera.getScene();
  47356. this._engine = this._scene.getEngine();
  47357. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47358. _this._keys = [];
  47359. });
  47360. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47361. var evt = info.event;
  47362. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47363. _this._ctrlPressed = evt.ctrlKey;
  47364. _this._altPressed = evt.altKey;
  47365. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47366. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47367. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47368. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47369. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47370. var index = _this._keys.indexOf(evt.keyCode);
  47371. if (index === -1) {
  47372. _this._keys.push(evt.keyCode);
  47373. }
  47374. if (evt.preventDefault) {
  47375. if (!noPreventDefault) {
  47376. evt.preventDefault();
  47377. }
  47378. }
  47379. }
  47380. }
  47381. else {
  47382. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47383. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47384. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47385. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47386. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47387. var index = _this._keys.indexOf(evt.keyCode);
  47388. if (index >= 0) {
  47389. _this._keys.splice(index, 1);
  47390. }
  47391. if (evt.preventDefault) {
  47392. if (!noPreventDefault) {
  47393. evt.preventDefault();
  47394. }
  47395. }
  47396. }
  47397. }
  47398. });
  47399. };
  47400. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47401. if (this._scene) {
  47402. if (this._onKeyboardObserver) {
  47403. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47404. }
  47405. if (this._onCanvasBlurObserver) {
  47406. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47407. }
  47408. this._onKeyboardObserver = null;
  47409. this._onCanvasBlurObserver = null;
  47410. }
  47411. this._keys = [];
  47412. };
  47413. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47414. if (this._onKeyboardObserver) {
  47415. var camera = this.camera;
  47416. for (var index = 0; index < this._keys.length; index++) {
  47417. var keyCode = this._keys[index];
  47418. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47419. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47420. camera.inertialPanningX -= 1 / this.panningSensibility;
  47421. }
  47422. else {
  47423. camera.inertialAlphaOffset -= 0.01;
  47424. }
  47425. }
  47426. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47427. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47428. camera.inertialPanningY += 1 / this.panningSensibility;
  47429. }
  47430. else if (this._altPressed && this.useAltToZoom) {
  47431. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47432. }
  47433. else {
  47434. camera.inertialBetaOffset -= 0.01;
  47435. }
  47436. }
  47437. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47438. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47439. camera.inertialPanningX += 1 / this.panningSensibility;
  47440. }
  47441. else {
  47442. camera.inertialAlphaOffset += 0.01;
  47443. }
  47444. }
  47445. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47446. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47447. camera.inertialPanningY -= 1 / this.panningSensibility;
  47448. }
  47449. else if (this._altPressed && this.useAltToZoom) {
  47450. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47451. }
  47452. else {
  47453. camera.inertialBetaOffset += 0.01;
  47454. }
  47455. }
  47456. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47457. camera.restoreState();
  47458. }
  47459. }
  47460. }
  47461. };
  47462. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47463. return "ArcRotateCameraKeyboardMoveInput";
  47464. };
  47465. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47466. return "keyboard";
  47467. };
  47468. __decorate([
  47469. BABYLON.serialize()
  47470. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47471. __decorate([
  47472. BABYLON.serialize()
  47473. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47474. __decorate([
  47475. BABYLON.serialize()
  47476. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47477. __decorate([
  47478. BABYLON.serialize()
  47479. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47480. __decorate([
  47481. BABYLON.serialize()
  47482. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47483. __decorate([
  47484. BABYLON.serialize()
  47485. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47486. __decorate([
  47487. BABYLON.serialize()
  47488. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47489. __decorate([
  47490. BABYLON.serialize()
  47491. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47492. return ArcRotateCameraKeyboardMoveInput;
  47493. }());
  47494. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47495. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47496. })(BABYLON || (BABYLON = {}));
  47497. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47498. var BABYLON;
  47499. (function (BABYLON) {
  47500. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47501. function ArcRotateCameraMouseWheelInput() {
  47502. this.wheelPrecision = 3.0;
  47503. /**
  47504. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47505. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47506. */
  47507. this.wheelDeltaPercentage = 0;
  47508. }
  47509. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47510. var _this = this;
  47511. this._wheel = function (p, s) {
  47512. //sanity check - this should be a PointerWheel event.
  47513. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47514. return;
  47515. var event = p.event;
  47516. var delta = 0;
  47517. if (event.wheelDelta) {
  47518. if (_this.wheelDeltaPercentage) {
  47519. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47520. if (event.wheelDelta > 0) {
  47521. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47522. }
  47523. else {
  47524. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47525. }
  47526. }
  47527. else {
  47528. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47529. }
  47530. }
  47531. else if (event.detail) {
  47532. delta = -event.detail / _this.wheelPrecision;
  47533. }
  47534. if (delta)
  47535. _this.camera.inertialRadiusOffset += delta;
  47536. if (event.preventDefault) {
  47537. if (!noPreventDefault) {
  47538. event.preventDefault();
  47539. }
  47540. }
  47541. };
  47542. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47543. };
  47544. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47545. if (this._observer && element) {
  47546. this.camera.getScene().onPointerObservable.remove(this._observer);
  47547. this._observer = null;
  47548. this._wheel = null;
  47549. }
  47550. };
  47551. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47552. return "ArcRotateCameraMouseWheelInput";
  47553. };
  47554. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47555. return "mousewheel";
  47556. };
  47557. __decorate([
  47558. BABYLON.serialize()
  47559. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47560. __decorate([
  47561. BABYLON.serialize()
  47562. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47563. return ArcRotateCameraMouseWheelInput;
  47564. }());
  47565. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47566. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47567. })(BABYLON || (BABYLON = {}));
  47568. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47569. var BABYLON;
  47570. (function (BABYLON) {
  47571. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47572. function ArcRotateCameraPointersInput() {
  47573. this.buttons = [0, 1, 2];
  47574. this.angularSensibilityX = 1000.0;
  47575. this.angularSensibilityY = 1000.0;
  47576. this.pinchPrecision = 12.0;
  47577. /**
  47578. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47579. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47580. */
  47581. this.pinchDeltaPercentage = 0;
  47582. this.panningSensibility = 1000.0;
  47583. this.multiTouchPanning = true;
  47584. this.multiTouchPanAndZoom = true;
  47585. this._isPanClick = false;
  47586. this.pinchInwards = true;
  47587. }
  47588. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47589. var _this = this;
  47590. var engine = this.camera.getEngine();
  47591. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47592. var pointA = null;
  47593. var pointB = null;
  47594. var previousPinchSquaredDistance = 0;
  47595. var initialDistance = 0;
  47596. var twoFingerActivityCount = 0;
  47597. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47598. this._pointerInput = function (p, s) {
  47599. var evt = p.event;
  47600. var isTouch = p.event.pointerType === "touch";
  47601. if (engine.isInVRExclusivePointerMode) {
  47602. return;
  47603. }
  47604. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47605. return;
  47606. }
  47607. var srcElement = (evt.srcElement || evt.target);
  47608. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47609. try {
  47610. srcElement.setPointerCapture(evt.pointerId);
  47611. }
  47612. catch (e) {
  47613. //Nothing to do with the error. Execution will continue.
  47614. }
  47615. // Manage panning with pan button click
  47616. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47617. // manage pointers
  47618. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47619. if (pointA === null) {
  47620. pointA = cacheSoloPointer;
  47621. }
  47622. else if (pointB === null) {
  47623. pointB = cacheSoloPointer;
  47624. }
  47625. if (!noPreventDefault) {
  47626. evt.preventDefault();
  47627. element.focus();
  47628. }
  47629. }
  47630. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47631. _this.camera.restoreState();
  47632. }
  47633. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47634. try {
  47635. srcElement.releasePointerCapture(evt.pointerId);
  47636. }
  47637. catch (e) {
  47638. //Nothing to do with the error.
  47639. }
  47640. cacheSoloPointer = null;
  47641. previousPinchSquaredDistance = 0;
  47642. previousMultiTouchPanPosition.isPaning = false;
  47643. previousMultiTouchPanPosition.isPinching = false;
  47644. twoFingerActivityCount = 0;
  47645. initialDistance = 0;
  47646. if (!isTouch) {
  47647. pointB = null; // Mouse and pen are mono pointer
  47648. }
  47649. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47650. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47651. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47652. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47653. if (engine._badOS) {
  47654. pointA = pointB = null;
  47655. }
  47656. else {
  47657. //only remove the impacted pointer in case of multitouch allowing on most
  47658. //platforms switching from rotate to zoom and pan seamlessly.
  47659. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47660. pointA = pointB;
  47661. pointB = null;
  47662. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47663. }
  47664. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47665. pointB = null;
  47666. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47667. }
  47668. else {
  47669. pointA = pointB = null;
  47670. }
  47671. }
  47672. if (!noPreventDefault) {
  47673. evt.preventDefault();
  47674. }
  47675. }
  47676. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47677. if (!noPreventDefault) {
  47678. evt.preventDefault();
  47679. }
  47680. // One button down
  47681. if (pointA && pointB === null && cacheSoloPointer) {
  47682. if (_this.panningSensibility !== 0 &&
  47683. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47684. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47685. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47686. }
  47687. else {
  47688. var offsetX = evt.clientX - cacheSoloPointer.x;
  47689. var offsetY = evt.clientY - cacheSoloPointer.y;
  47690. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47691. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47692. }
  47693. cacheSoloPointer.x = evt.clientX;
  47694. cacheSoloPointer.y = evt.clientY;
  47695. }
  47696. // Two buttons down: pinch/pan
  47697. else if (pointA && pointB) {
  47698. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47699. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47700. ed.x = evt.clientX;
  47701. ed.y = evt.clientY;
  47702. var direction = _this.pinchInwards ? 1 : -1;
  47703. var distX = pointA.x - pointB.x;
  47704. var distY = pointA.y - pointB.y;
  47705. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47706. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47707. if (previousPinchSquaredDistance === 0) {
  47708. initialDistance = pinchDistance;
  47709. previousPinchSquaredDistance = pinchSquaredDistance;
  47710. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47711. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47712. return;
  47713. }
  47714. if (_this.multiTouchPanAndZoom) {
  47715. if (_this.pinchDeltaPercentage) {
  47716. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47717. }
  47718. else {
  47719. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47720. (_this.pinchPrecision *
  47721. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47722. direction);
  47723. }
  47724. if (_this.panningSensibility !== 0) {
  47725. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47726. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47727. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47728. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47729. previousMultiTouchPanPosition.x = pointersCenterX;
  47730. previousMultiTouchPanPosition.y = pointersCenterY;
  47731. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47732. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47733. }
  47734. }
  47735. else {
  47736. twoFingerActivityCount++;
  47737. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47738. if (_this.pinchDeltaPercentage) {
  47739. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47740. }
  47741. else {
  47742. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47743. (_this.pinchPrecision *
  47744. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47745. direction);
  47746. }
  47747. previousMultiTouchPanPosition.isPaning = false;
  47748. previousMultiTouchPanPosition.isPinching = true;
  47749. }
  47750. else {
  47751. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47752. if (!previousMultiTouchPanPosition.isPaning) {
  47753. previousMultiTouchPanPosition.isPaning = true;
  47754. previousMultiTouchPanPosition.isPinching = false;
  47755. previousMultiTouchPanPosition.x = ed.x;
  47756. previousMultiTouchPanPosition.y = ed.y;
  47757. return;
  47758. }
  47759. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47760. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47761. }
  47762. }
  47763. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47764. previousMultiTouchPanPosition.x = ed.x;
  47765. previousMultiTouchPanPosition.y = ed.y;
  47766. }
  47767. }
  47768. previousPinchSquaredDistance = pinchSquaredDistance;
  47769. }
  47770. }
  47771. };
  47772. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47773. this._onContextMenu = function (evt) {
  47774. evt.preventDefault();
  47775. };
  47776. if (!this.camera._useCtrlForPanning) {
  47777. element.addEventListener("contextmenu", this._onContextMenu, false);
  47778. }
  47779. this._onLostFocus = function () {
  47780. //this._keys = [];
  47781. pointA = pointB = null;
  47782. previousPinchSquaredDistance = 0;
  47783. previousMultiTouchPanPosition.isPaning = false;
  47784. previousMultiTouchPanPosition.isPinching = false;
  47785. twoFingerActivityCount = 0;
  47786. cacheSoloPointer = null;
  47787. initialDistance = 0;
  47788. };
  47789. this._onMouseMove = function (evt) {
  47790. if (!engine.isPointerLock) {
  47791. return;
  47792. }
  47793. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47794. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47795. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47796. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47797. if (!noPreventDefault) {
  47798. evt.preventDefault();
  47799. }
  47800. };
  47801. this._onGestureStart = function (e) {
  47802. if (window.MSGesture === undefined) {
  47803. return;
  47804. }
  47805. if (!_this._MSGestureHandler) {
  47806. _this._MSGestureHandler = new MSGesture();
  47807. _this._MSGestureHandler.target = element;
  47808. }
  47809. _this._MSGestureHandler.addPointer(e.pointerId);
  47810. };
  47811. this._onGesture = function (e) {
  47812. _this.camera.radius *= e.scale;
  47813. if (e.preventDefault) {
  47814. if (!noPreventDefault) {
  47815. e.stopPropagation();
  47816. e.preventDefault();
  47817. }
  47818. }
  47819. };
  47820. element.addEventListener("mousemove", this._onMouseMove, false);
  47821. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47822. element.addEventListener("MSGestureChange", this._onGesture, false);
  47823. BABYLON.Tools.RegisterTopRootEvents([
  47824. { name: "blur", handler: this._onLostFocus }
  47825. ]);
  47826. };
  47827. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47828. if (this._onLostFocus) {
  47829. BABYLON.Tools.UnregisterTopRootEvents([
  47830. { name: "blur", handler: this._onLostFocus }
  47831. ]);
  47832. }
  47833. if (element && this._observer) {
  47834. this.camera.getScene().onPointerObservable.remove(this._observer);
  47835. this._observer = null;
  47836. if (this._onContextMenu) {
  47837. element.removeEventListener("contextmenu", this._onContextMenu);
  47838. }
  47839. if (this._onMouseMove) {
  47840. element.removeEventListener("mousemove", this._onMouseMove);
  47841. }
  47842. if (this._onGestureStart) {
  47843. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47844. }
  47845. if (this._onGesture) {
  47846. element.removeEventListener("MSGestureChange", this._onGesture);
  47847. }
  47848. this._isPanClick = false;
  47849. this.pinchInwards = true;
  47850. this._onMouseMove = null;
  47851. this._onGestureStart = null;
  47852. this._onGesture = null;
  47853. this._MSGestureHandler = null;
  47854. this._onLostFocus = null;
  47855. this._onContextMenu = null;
  47856. }
  47857. };
  47858. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47859. return "ArcRotateCameraPointersInput";
  47860. };
  47861. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47862. return "pointers";
  47863. };
  47864. __decorate([
  47865. BABYLON.serialize()
  47866. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47867. __decorate([
  47868. BABYLON.serialize()
  47869. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47870. __decorate([
  47871. BABYLON.serialize()
  47872. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47873. __decorate([
  47874. BABYLON.serialize()
  47875. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47876. __decorate([
  47877. BABYLON.serialize()
  47878. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47879. __decorate([
  47880. BABYLON.serialize()
  47881. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47882. __decorate([
  47883. BABYLON.serialize()
  47884. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47885. __decorate([
  47886. BABYLON.serialize()
  47887. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47888. return ArcRotateCameraPointersInput;
  47889. }());
  47890. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47891. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47892. })(BABYLON || (BABYLON = {}));
  47893. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47894. var BABYLON;
  47895. (function (BABYLON) {
  47896. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47897. __extends(ArcRotateCameraInputsManager, _super);
  47898. function ArcRotateCameraInputsManager(camera) {
  47899. return _super.call(this, camera) || this;
  47900. }
  47901. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47902. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47903. return this;
  47904. };
  47905. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47906. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47907. return this;
  47908. };
  47909. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47910. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47911. return this;
  47912. };
  47913. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47914. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47915. return this;
  47916. };
  47917. return ArcRotateCameraInputsManager;
  47918. }(BABYLON.CameraInputsManager));
  47919. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47920. })(BABYLON || (BABYLON = {}));
  47921. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47922. var BABYLON;
  47923. (function (BABYLON) {
  47924. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47925. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47926. });
  47927. var ArcRotateCamera = /** @class */ (function (_super) {
  47928. __extends(ArcRotateCamera, _super);
  47929. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47930. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47931. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47932. _this.inertialAlphaOffset = 0;
  47933. _this.inertialBetaOffset = 0;
  47934. _this.inertialRadiusOffset = 0;
  47935. _this.lowerAlphaLimit = null;
  47936. _this.upperAlphaLimit = null;
  47937. _this.lowerBetaLimit = 0.01;
  47938. _this.upperBetaLimit = Math.PI;
  47939. _this.lowerRadiusLimit = null;
  47940. _this.upperRadiusLimit = null;
  47941. _this.inertialPanningX = 0;
  47942. _this.inertialPanningY = 0;
  47943. _this.pinchToPanMaxDistance = 20;
  47944. _this.panningDistanceLimit = null;
  47945. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47946. _this.panningInertia = 0.9;
  47947. //-- end properties for backward compatibility for inputs
  47948. _this.zoomOnFactor = 1;
  47949. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47950. _this.allowUpsideDown = true;
  47951. /** @hidden */
  47952. _this._viewMatrix = new BABYLON.Matrix();
  47953. // Panning
  47954. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47955. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47956. _this.checkCollisions = false;
  47957. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47958. _this._previousPosition = BABYLON.Vector3.Zero();
  47959. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47960. _this._newPosition = BABYLON.Vector3.Zero();
  47961. _this._computationVector = BABYLON.Vector3.Zero();
  47962. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47963. if (collidedMesh === void 0) { collidedMesh = null; }
  47964. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47965. newPosition.multiplyInPlace(_this._collider._radius);
  47966. }
  47967. if (!collidedMesh) {
  47968. _this._previousPosition.copyFrom(_this.position);
  47969. }
  47970. else {
  47971. _this.setPosition(newPosition);
  47972. if (_this.onCollide) {
  47973. _this.onCollide(collidedMesh);
  47974. }
  47975. }
  47976. // Recompute because of constraints
  47977. var cosa = Math.cos(_this.alpha);
  47978. var sina = Math.sin(_this.alpha);
  47979. var cosb = Math.cos(_this.beta);
  47980. var sinb = Math.sin(_this.beta);
  47981. if (sinb === 0) {
  47982. sinb = 0.0001;
  47983. }
  47984. var target = _this._getTargetPosition();
  47985. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47986. target.addToRef(_this._computationVector, _this._newPosition);
  47987. _this.position.copyFrom(_this._newPosition);
  47988. var up = _this.upVector;
  47989. if (_this.allowUpsideDown && _this.beta < 0) {
  47990. up = up.clone();
  47991. up = up.negate();
  47992. }
  47993. _this._computeViewMatrix(_this.position, target, up);
  47994. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47995. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47996. _this._collisionTriggered = false;
  47997. };
  47998. _this._target = BABYLON.Vector3.Zero();
  47999. if (target) {
  48000. _this.setTarget(target);
  48001. }
  48002. _this.alpha = alpha;
  48003. _this.beta = beta;
  48004. _this.radius = radius;
  48005. _this.getViewMatrix();
  48006. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48007. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48008. return _this;
  48009. }
  48010. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48011. get: function () {
  48012. return this._target;
  48013. },
  48014. set: function (value) {
  48015. this.setTarget(value);
  48016. },
  48017. enumerable: true,
  48018. configurable: true
  48019. });
  48020. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48021. //-- begin properties for backward compatibility for inputs
  48022. get: function () {
  48023. var pointers = this.inputs.attached["pointers"];
  48024. if (pointers)
  48025. return pointers.angularSensibilityX;
  48026. return 0;
  48027. },
  48028. set: function (value) {
  48029. var pointers = this.inputs.attached["pointers"];
  48030. if (pointers) {
  48031. pointers.angularSensibilityX = value;
  48032. }
  48033. },
  48034. enumerable: true,
  48035. configurable: true
  48036. });
  48037. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48038. get: function () {
  48039. var pointers = this.inputs.attached["pointers"];
  48040. if (pointers)
  48041. return pointers.angularSensibilityY;
  48042. return 0;
  48043. },
  48044. set: function (value) {
  48045. var pointers = this.inputs.attached["pointers"];
  48046. if (pointers) {
  48047. pointers.angularSensibilityY = value;
  48048. }
  48049. },
  48050. enumerable: true,
  48051. configurable: true
  48052. });
  48053. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48054. get: function () {
  48055. var pointers = this.inputs.attached["pointers"];
  48056. if (pointers)
  48057. return pointers.pinchPrecision;
  48058. return 0;
  48059. },
  48060. set: function (value) {
  48061. var pointers = this.inputs.attached["pointers"];
  48062. if (pointers) {
  48063. pointers.pinchPrecision = value;
  48064. }
  48065. },
  48066. enumerable: true,
  48067. configurable: true
  48068. });
  48069. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48070. get: function () {
  48071. var pointers = this.inputs.attached["pointers"];
  48072. if (pointers)
  48073. return pointers.pinchDeltaPercentage;
  48074. return 0;
  48075. },
  48076. set: function (value) {
  48077. var pointers = this.inputs.attached["pointers"];
  48078. if (pointers) {
  48079. pointers.pinchDeltaPercentage = value;
  48080. }
  48081. },
  48082. enumerable: true,
  48083. configurable: true
  48084. });
  48085. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48086. get: function () {
  48087. var pointers = this.inputs.attached["pointers"];
  48088. if (pointers)
  48089. return pointers.panningSensibility;
  48090. return 0;
  48091. },
  48092. set: function (value) {
  48093. var pointers = this.inputs.attached["pointers"];
  48094. if (pointers) {
  48095. pointers.panningSensibility = value;
  48096. }
  48097. },
  48098. enumerable: true,
  48099. configurable: true
  48100. });
  48101. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48102. get: function () {
  48103. var keyboard = this.inputs.attached["keyboard"];
  48104. if (keyboard)
  48105. return keyboard.keysUp;
  48106. return [];
  48107. },
  48108. set: function (value) {
  48109. var keyboard = this.inputs.attached["keyboard"];
  48110. if (keyboard)
  48111. keyboard.keysUp = value;
  48112. },
  48113. enumerable: true,
  48114. configurable: true
  48115. });
  48116. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48117. get: function () {
  48118. var keyboard = this.inputs.attached["keyboard"];
  48119. if (keyboard)
  48120. return keyboard.keysDown;
  48121. return [];
  48122. },
  48123. set: function (value) {
  48124. var keyboard = this.inputs.attached["keyboard"];
  48125. if (keyboard)
  48126. keyboard.keysDown = value;
  48127. },
  48128. enumerable: true,
  48129. configurable: true
  48130. });
  48131. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48132. get: function () {
  48133. var keyboard = this.inputs.attached["keyboard"];
  48134. if (keyboard)
  48135. return keyboard.keysLeft;
  48136. return [];
  48137. },
  48138. set: function (value) {
  48139. var keyboard = this.inputs.attached["keyboard"];
  48140. if (keyboard)
  48141. keyboard.keysLeft = value;
  48142. },
  48143. enumerable: true,
  48144. configurable: true
  48145. });
  48146. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48147. get: function () {
  48148. var keyboard = this.inputs.attached["keyboard"];
  48149. if (keyboard)
  48150. return keyboard.keysRight;
  48151. return [];
  48152. },
  48153. set: function (value) {
  48154. var keyboard = this.inputs.attached["keyboard"];
  48155. if (keyboard)
  48156. keyboard.keysRight = value;
  48157. },
  48158. enumerable: true,
  48159. configurable: true
  48160. });
  48161. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48162. get: function () {
  48163. var mousewheel = this.inputs.attached["mousewheel"];
  48164. if (mousewheel)
  48165. return mousewheel.wheelPrecision;
  48166. return 0;
  48167. },
  48168. set: function (value) {
  48169. var mousewheel = this.inputs.attached["mousewheel"];
  48170. if (mousewheel)
  48171. mousewheel.wheelPrecision = value;
  48172. },
  48173. enumerable: true,
  48174. configurable: true
  48175. });
  48176. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48177. get: function () {
  48178. var mousewheel = this.inputs.attached["mousewheel"];
  48179. if (mousewheel)
  48180. return mousewheel.wheelDeltaPercentage;
  48181. return 0;
  48182. },
  48183. set: function (value) {
  48184. var mousewheel = this.inputs.attached["mousewheel"];
  48185. if (mousewheel)
  48186. mousewheel.wheelDeltaPercentage = value;
  48187. },
  48188. enumerable: true,
  48189. configurable: true
  48190. });
  48191. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48192. get: function () {
  48193. return this._bouncingBehavior;
  48194. },
  48195. enumerable: true,
  48196. configurable: true
  48197. });
  48198. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48199. get: function () {
  48200. return this._bouncingBehavior != null;
  48201. },
  48202. set: function (value) {
  48203. if (value === this.useBouncingBehavior) {
  48204. return;
  48205. }
  48206. if (value) {
  48207. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48208. this.addBehavior(this._bouncingBehavior);
  48209. }
  48210. else if (this._bouncingBehavior) {
  48211. this.removeBehavior(this._bouncingBehavior);
  48212. this._bouncingBehavior = null;
  48213. }
  48214. },
  48215. enumerable: true,
  48216. configurable: true
  48217. });
  48218. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48219. get: function () {
  48220. return this._framingBehavior;
  48221. },
  48222. enumerable: true,
  48223. configurable: true
  48224. });
  48225. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48226. get: function () {
  48227. return this._framingBehavior != null;
  48228. },
  48229. set: function (value) {
  48230. if (value === this.useFramingBehavior) {
  48231. return;
  48232. }
  48233. if (value) {
  48234. this._framingBehavior = new BABYLON.FramingBehavior();
  48235. this.addBehavior(this._framingBehavior);
  48236. }
  48237. else if (this._framingBehavior) {
  48238. this.removeBehavior(this._framingBehavior);
  48239. this._framingBehavior = null;
  48240. }
  48241. },
  48242. enumerable: true,
  48243. configurable: true
  48244. });
  48245. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48246. get: function () {
  48247. return this._autoRotationBehavior;
  48248. },
  48249. enumerable: true,
  48250. configurable: true
  48251. });
  48252. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48253. get: function () {
  48254. return this._autoRotationBehavior != null;
  48255. },
  48256. set: function (value) {
  48257. if (value === this.useAutoRotationBehavior) {
  48258. return;
  48259. }
  48260. if (value) {
  48261. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48262. this.addBehavior(this._autoRotationBehavior);
  48263. }
  48264. else if (this._autoRotationBehavior) {
  48265. this.removeBehavior(this._autoRotationBehavior);
  48266. this._autoRotationBehavior = null;
  48267. }
  48268. },
  48269. enumerable: true,
  48270. configurable: true
  48271. });
  48272. // Cache
  48273. /** @hidden */
  48274. ArcRotateCamera.prototype._initCache = function () {
  48275. _super.prototype._initCache.call(this);
  48276. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48277. this._cache.alpha = undefined;
  48278. this._cache.beta = undefined;
  48279. this._cache.radius = undefined;
  48280. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48281. };
  48282. /** @hidden */
  48283. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48284. if (!ignoreParentClass) {
  48285. _super.prototype._updateCache.call(this);
  48286. }
  48287. this._cache._target.copyFrom(this._getTargetPosition());
  48288. this._cache.alpha = this.alpha;
  48289. this._cache.beta = this.beta;
  48290. this._cache.radius = this.radius;
  48291. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48292. };
  48293. ArcRotateCamera.prototype._getTargetPosition = function () {
  48294. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48295. var pos = this._targetHost.getAbsolutePosition();
  48296. if (this._targetBoundingCenter) {
  48297. pos.addToRef(this._targetBoundingCenter, this._target);
  48298. }
  48299. else {
  48300. this._target.copyFrom(pos);
  48301. }
  48302. }
  48303. var lockedTargetPosition = this._getLockedTargetPosition();
  48304. if (lockedTargetPosition) {
  48305. return lockedTargetPosition;
  48306. }
  48307. return this._target;
  48308. };
  48309. ArcRotateCamera.prototype.storeState = function () {
  48310. this._storedAlpha = this.alpha;
  48311. this._storedBeta = this.beta;
  48312. this._storedRadius = this.radius;
  48313. this._storedTarget = this._getTargetPosition().clone();
  48314. return _super.prototype.storeState.call(this);
  48315. };
  48316. /**
  48317. * @hidden
  48318. * Restored camera state. You must call storeState() first
  48319. */
  48320. ArcRotateCamera.prototype._restoreStateValues = function () {
  48321. if (!_super.prototype._restoreStateValues.call(this)) {
  48322. return false;
  48323. }
  48324. this.alpha = this._storedAlpha;
  48325. this.beta = this._storedBeta;
  48326. this.radius = this._storedRadius;
  48327. this.setTarget(this._storedTarget.clone());
  48328. this.inertialAlphaOffset = 0;
  48329. this.inertialBetaOffset = 0;
  48330. this.inertialRadiusOffset = 0;
  48331. this.inertialPanningX = 0;
  48332. this.inertialPanningY = 0;
  48333. return true;
  48334. };
  48335. // Synchronized
  48336. /** @hidden */
  48337. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48338. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48339. return false;
  48340. return this._cache._target.equals(this._getTargetPosition())
  48341. && this._cache.alpha === this.alpha
  48342. && this._cache.beta === this.beta
  48343. && this._cache.radius === this.radius
  48344. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48345. };
  48346. // Methods
  48347. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48348. var _this = this;
  48349. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48350. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48351. this._useCtrlForPanning = useCtrlForPanning;
  48352. this._panningMouseButton = panningMouseButton;
  48353. this.inputs.attachElement(element, noPreventDefault);
  48354. this._reset = function () {
  48355. _this.inertialAlphaOffset = 0;
  48356. _this.inertialBetaOffset = 0;
  48357. _this.inertialRadiusOffset = 0;
  48358. _this.inertialPanningX = 0;
  48359. _this.inertialPanningY = 0;
  48360. };
  48361. };
  48362. ArcRotateCamera.prototype.detachControl = function (element) {
  48363. this.inputs.detachElement(element);
  48364. if (this._reset) {
  48365. this._reset();
  48366. }
  48367. };
  48368. /** @hidden */
  48369. ArcRotateCamera.prototype._checkInputs = function () {
  48370. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48371. if (this._collisionTriggered) {
  48372. return;
  48373. }
  48374. this.inputs.checkInputs();
  48375. // Inertia
  48376. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48377. var inertialAlphaOffset = this.inertialAlphaOffset;
  48378. if (this.beta <= 0)
  48379. inertialAlphaOffset *= -1;
  48380. if (this.getScene().useRightHandedSystem)
  48381. inertialAlphaOffset *= -1;
  48382. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48383. inertialAlphaOffset *= -1;
  48384. this.alpha += inertialAlphaOffset;
  48385. this.beta += this.inertialBetaOffset;
  48386. this.radius -= this.inertialRadiusOffset;
  48387. this.inertialAlphaOffset *= this.inertia;
  48388. this.inertialBetaOffset *= this.inertia;
  48389. this.inertialRadiusOffset *= this.inertia;
  48390. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48391. this.inertialAlphaOffset = 0;
  48392. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48393. this.inertialBetaOffset = 0;
  48394. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48395. this.inertialRadiusOffset = 0;
  48396. }
  48397. // Panning inertia
  48398. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48399. if (!this._localDirection) {
  48400. this._localDirection = BABYLON.Vector3.Zero();
  48401. this._transformedDirection = BABYLON.Vector3.Zero();
  48402. }
  48403. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48404. this._localDirection.multiplyInPlace(this.panningAxis);
  48405. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48406. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48407. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48408. if (!this.panningAxis.y) {
  48409. this._transformedDirection.y = 0;
  48410. }
  48411. if (!this._targetHost) {
  48412. if (this.panningDistanceLimit) {
  48413. this._transformedDirection.addInPlace(this._target);
  48414. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48415. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48416. this._target.copyFrom(this._transformedDirection);
  48417. }
  48418. }
  48419. else {
  48420. this._target.addInPlace(this._transformedDirection);
  48421. }
  48422. }
  48423. this.inertialPanningX *= this.panningInertia;
  48424. this.inertialPanningY *= this.panningInertia;
  48425. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48426. this.inertialPanningX = 0;
  48427. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48428. this.inertialPanningY = 0;
  48429. }
  48430. // Limits
  48431. this._checkLimits();
  48432. _super.prototype._checkInputs.call(this);
  48433. };
  48434. ArcRotateCamera.prototype._checkLimits = function () {
  48435. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48436. if (this.allowUpsideDown && this.beta > Math.PI) {
  48437. this.beta = this.beta - (2 * Math.PI);
  48438. }
  48439. }
  48440. else {
  48441. if (this.beta < this.lowerBetaLimit) {
  48442. this.beta = this.lowerBetaLimit;
  48443. }
  48444. }
  48445. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48446. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48447. this.beta = this.beta + (2 * Math.PI);
  48448. }
  48449. }
  48450. else {
  48451. if (this.beta > this.upperBetaLimit) {
  48452. this.beta = this.upperBetaLimit;
  48453. }
  48454. }
  48455. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  48456. this.alpha = this.lowerAlphaLimit;
  48457. }
  48458. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  48459. this.alpha = this.upperAlphaLimit;
  48460. }
  48461. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  48462. this.radius = this.lowerRadiusLimit;
  48463. }
  48464. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  48465. this.radius = this.upperRadiusLimit;
  48466. }
  48467. };
  48468. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48469. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48470. this.radius = this._computationVector.length();
  48471. if (this.radius === 0) {
  48472. this.radius = 0.0001; // Just to avoid division by zero
  48473. }
  48474. // Alpha
  48475. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48476. if (this._computationVector.z < 0) {
  48477. this.alpha = 2 * Math.PI - this.alpha;
  48478. }
  48479. // Beta
  48480. this.beta = Math.acos(this._computationVector.y / this.radius);
  48481. this._checkLimits();
  48482. };
  48483. ArcRotateCamera.prototype.setPosition = function (position) {
  48484. if (this.position.equals(position)) {
  48485. return;
  48486. }
  48487. this.position.copyFrom(position);
  48488. this.rebuildAnglesAndRadius();
  48489. };
  48490. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48491. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48492. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48493. if (target.getBoundingInfo) {
  48494. if (toBoundingCenter) {
  48495. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48496. }
  48497. else {
  48498. this._targetBoundingCenter = null;
  48499. }
  48500. this._targetHost = target;
  48501. this._target = this._getTargetPosition();
  48502. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48503. }
  48504. else {
  48505. var newTarget = target;
  48506. var currentTarget = this._getTargetPosition();
  48507. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48508. return;
  48509. }
  48510. this._targetHost = null;
  48511. this._target = newTarget;
  48512. this._targetBoundingCenter = null;
  48513. this.onMeshTargetChangedObservable.notifyObservers(null);
  48514. }
  48515. this.rebuildAnglesAndRadius();
  48516. };
  48517. /** @hidden */
  48518. ArcRotateCamera.prototype._getViewMatrix = function () {
  48519. // Compute
  48520. var cosa = Math.cos(this.alpha);
  48521. var sina = Math.sin(this.alpha);
  48522. var cosb = Math.cos(this.beta);
  48523. var sinb = Math.sin(this.beta);
  48524. if (sinb === 0) {
  48525. sinb = 0.0001;
  48526. }
  48527. var target = this._getTargetPosition();
  48528. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48529. target.addToRef(this._computationVector, this._newPosition);
  48530. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48531. if (!this._collider) {
  48532. this._collider = new BABYLON.Collider();
  48533. }
  48534. this._collider._radius = this.collisionRadius;
  48535. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48536. this._collisionTriggered = true;
  48537. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48538. }
  48539. else {
  48540. this.position.copyFrom(this._newPosition);
  48541. var up = this.upVector;
  48542. if (this.allowUpsideDown && sinb < 0) {
  48543. up = up.clone();
  48544. up = up.negate();
  48545. }
  48546. this._computeViewMatrix(this.position, target, up);
  48547. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48548. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48549. }
  48550. this._currentTarget = target;
  48551. return this._viewMatrix;
  48552. };
  48553. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48554. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48555. meshes = meshes || this.getScene().meshes;
  48556. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48557. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48558. this.radius = distance * this.zoomOnFactor;
  48559. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48560. };
  48561. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48562. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48563. var meshesOrMinMaxVector;
  48564. var distance;
  48565. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48566. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48567. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48568. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48569. }
  48570. else { //minMaxVector and distance
  48571. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48572. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48573. distance = minMaxVectorAndDistance.distance;
  48574. }
  48575. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48576. if (!doNotUpdateMaxZ) {
  48577. this.maxZ = distance * 2;
  48578. }
  48579. };
  48580. /**
  48581. * @override
  48582. * Override Camera.createRigCamera
  48583. */
  48584. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48585. var alphaShift = 0;
  48586. switch (this.cameraRigMode) {
  48587. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48588. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48589. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48590. case BABYLON.Camera.RIG_MODE_VR:
  48591. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48592. break;
  48593. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48594. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48595. break;
  48596. }
  48597. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48598. rigCam._cameraRigParams = {};
  48599. return rigCam;
  48600. };
  48601. /**
  48602. * @hidden
  48603. * @override
  48604. * Override Camera._updateRigCameras
  48605. */
  48606. ArcRotateCamera.prototype._updateRigCameras = function () {
  48607. var camLeft = this._rigCameras[0];
  48608. var camRight = this._rigCameras[1];
  48609. camLeft.beta = camRight.beta = this.beta;
  48610. camLeft.radius = camRight.radius = this.radius;
  48611. switch (this.cameraRigMode) {
  48612. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48613. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48614. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48615. case BABYLON.Camera.RIG_MODE_VR:
  48616. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48617. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48618. break;
  48619. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48620. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48621. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48622. break;
  48623. }
  48624. _super.prototype._updateRigCameras.call(this);
  48625. };
  48626. ArcRotateCamera.prototype.dispose = function () {
  48627. this.inputs.clear();
  48628. _super.prototype.dispose.call(this);
  48629. };
  48630. ArcRotateCamera.prototype.getClassName = function () {
  48631. return "ArcRotateCamera";
  48632. };
  48633. __decorate([
  48634. BABYLON.serialize()
  48635. ], ArcRotateCamera.prototype, "alpha", void 0);
  48636. __decorate([
  48637. BABYLON.serialize()
  48638. ], ArcRotateCamera.prototype, "beta", void 0);
  48639. __decorate([
  48640. BABYLON.serialize()
  48641. ], ArcRotateCamera.prototype, "radius", void 0);
  48642. __decorate([
  48643. BABYLON.serializeAsVector3("target")
  48644. ], ArcRotateCamera.prototype, "_target", void 0);
  48645. __decorate([
  48646. BABYLON.serialize()
  48647. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48648. __decorate([
  48649. BABYLON.serialize()
  48650. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48651. __decorate([
  48652. BABYLON.serialize()
  48653. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48654. __decorate([
  48655. BABYLON.serialize()
  48656. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48657. __decorate([
  48658. BABYLON.serialize()
  48659. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48660. __decorate([
  48661. BABYLON.serialize()
  48662. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48663. __decorate([
  48664. BABYLON.serialize()
  48665. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48666. __decorate([
  48667. BABYLON.serialize()
  48668. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48669. __decorate([
  48670. BABYLON.serialize()
  48671. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48672. __decorate([
  48673. BABYLON.serialize()
  48674. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48675. __decorate([
  48676. BABYLON.serialize()
  48677. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48678. __decorate([
  48679. BABYLON.serialize()
  48680. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48681. __decorate([
  48682. BABYLON.serialize()
  48683. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48684. __decorate([
  48685. BABYLON.serializeAsVector3()
  48686. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48687. __decorate([
  48688. BABYLON.serialize()
  48689. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48690. __decorate([
  48691. BABYLON.serialize()
  48692. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48693. __decorate([
  48694. BABYLON.serialize()
  48695. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48696. return ArcRotateCamera;
  48697. }(BABYLON.TargetCamera));
  48698. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48699. })(BABYLON || (BABYLON = {}));
  48700. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48701. var BABYLON;
  48702. (function (BABYLON) {
  48703. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48704. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48705. });
  48706. /**
  48707. * The HemisphericLight simulates the ambient environment light,
  48708. * so the passed direction is the light reflection direction, not the incoming direction.
  48709. */
  48710. var HemisphericLight = /** @class */ (function (_super) {
  48711. __extends(HemisphericLight, _super);
  48712. /**
  48713. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48714. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48715. * The HemisphericLight can't cast shadows.
  48716. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48717. * @param name The friendly name of the light
  48718. * @param direction The direction of the light reflection
  48719. * @param scene The scene the light belongs to
  48720. */
  48721. function HemisphericLight(name, direction, scene) {
  48722. var _this = _super.call(this, name, scene) || this;
  48723. /**
  48724. * The groundColor is the light in the opposite direction to the one specified during creation.
  48725. * 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.
  48726. */
  48727. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48728. _this.direction = direction || BABYLON.Vector3.Up();
  48729. return _this;
  48730. }
  48731. HemisphericLight.prototype._buildUniformLayout = function () {
  48732. this._uniformBuffer.addUniform("vLightData", 4);
  48733. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48734. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48735. this._uniformBuffer.addUniform("vLightGround", 3);
  48736. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48737. this._uniformBuffer.addUniform("depthValues", 2);
  48738. this._uniformBuffer.create();
  48739. };
  48740. /**
  48741. * Returns the string "HemisphericLight".
  48742. * @return The class name
  48743. */
  48744. HemisphericLight.prototype.getClassName = function () {
  48745. return "HemisphericLight";
  48746. };
  48747. /**
  48748. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48749. * Returns the updated direction.
  48750. * @param target The target the direction should point to
  48751. * @return The computed direction
  48752. */
  48753. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48754. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48755. return this.direction;
  48756. };
  48757. /**
  48758. * Returns the shadow generator associated to the light.
  48759. * @returns Always null for hemispheric lights because it does not support shadows.
  48760. */
  48761. HemisphericLight.prototype.getShadowGenerator = function () {
  48762. return null;
  48763. };
  48764. /**
  48765. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48766. * @param effect The effect to update
  48767. * @param lightIndex The index of the light in the effect to update
  48768. * @returns The hemispheric light
  48769. */
  48770. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48771. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48772. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48773. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48774. return this;
  48775. };
  48776. /**
  48777. * @hidden internal use only.
  48778. */
  48779. HemisphericLight.prototype._getWorldMatrix = function () {
  48780. if (!this._worldMatrix) {
  48781. this._worldMatrix = BABYLON.Matrix.Identity();
  48782. }
  48783. return this._worldMatrix;
  48784. };
  48785. /**
  48786. * Returns the integer 3.
  48787. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48788. */
  48789. HemisphericLight.prototype.getTypeID = function () {
  48790. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48791. };
  48792. /**
  48793. * Prepares the list of defines specific to the light type.
  48794. * @param defines the list of defines
  48795. * @param lightIndex defines the index of the light for the effect
  48796. */
  48797. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48798. defines["HEMILIGHT" + lightIndex] = true;
  48799. };
  48800. __decorate([
  48801. BABYLON.serializeAsColor3()
  48802. ], HemisphericLight.prototype, "groundColor", void 0);
  48803. __decorate([
  48804. BABYLON.serializeAsVector3()
  48805. ], HemisphericLight.prototype, "direction", void 0);
  48806. return HemisphericLight;
  48807. }(BABYLON.Light));
  48808. BABYLON.HemisphericLight = HemisphericLight;
  48809. })(BABYLON || (BABYLON = {}));
  48810. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48811. var BABYLON;
  48812. (function (BABYLON) {
  48813. /**
  48814. * Base implementation IShadowLight
  48815. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48816. */
  48817. var ShadowLight = /** @class */ (function (_super) {
  48818. __extends(ShadowLight, _super);
  48819. function ShadowLight() {
  48820. var _this = _super !== null && _super.apply(this, arguments) || this;
  48821. _this._needProjectionMatrixCompute = true;
  48822. return _this;
  48823. }
  48824. ShadowLight.prototype._setPosition = function (value) {
  48825. this._position = value;
  48826. };
  48827. Object.defineProperty(ShadowLight.prototype, "position", {
  48828. /**
  48829. * Sets the position the shadow will be casted from. Also use as the light position for both
  48830. * point and spot lights.
  48831. */
  48832. get: function () {
  48833. return this._position;
  48834. },
  48835. /**
  48836. * Sets the position the shadow will be casted from. Also use as the light position for both
  48837. * point and spot lights.
  48838. */
  48839. set: function (value) {
  48840. this._setPosition(value);
  48841. },
  48842. enumerable: true,
  48843. configurable: true
  48844. });
  48845. ShadowLight.prototype._setDirection = function (value) {
  48846. this._direction = value;
  48847. };
  48848. Object.defineProperty(ShadowLight.prototype, "direction", {
  48849. /**
  48850. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48851. * Also use as the light direction on spot and directional lights.
  48852. */
  48853. get: function () {
  48854. return this._direction;
  48855. },
  48856. /**
  48857. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48858. * Also use as the light direction on spot and directional lights.
  48859. */
  48860. set: function (value) {
  48861. this._setDirection(value);
  48862. },
  48863. enumerable: true,
  48864. configurable: true
  48865. });
  48866. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48867. /**
  48868. * Gets the shadow projection clipping minimum z value.
  48869. */
  48870. get: function () {
  48871. return this._shadowMinZ;
  48872. },
  48873. /**
  48874. * Sets the shadow projection clipping minimum z value.
  48875. */
  48876. set: function (value) {
  48877. this._shadowMinZ = value;
  48878. this.forceProjectionMatrixCompute();
  48879. },
  48880. enumerable: true,
  48881. configurable: true
  48882. });
  48883. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48884. /**
  48885. * Sets the shadow projection clipping maximum z value.
  48886. */
  48887. get: function () {
  48888. return this._shadowMaxZ;
  48889. },
  48890. /**
  48891. * Gets the shadow projection clipping maximum z value.
  48892. */
  48893. set: function (value) {
  48894. this._shadowMaxZ = value;
  48895. this.forceProjectionMatrixCompute();
  48896. },
  48897. enumerable: true,
  48898. configurable: true
  48899. });
  48900. /**
  48901. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48902. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48903. */
  48904. ShadowLight.prototype.computeTransformedInformation = function () {
  48905. if (this.parent && this.parent.getWorldMatrix) {
  48906. if (!this.transformedPosition) {
  48907. this.transformedPosition = BABYLON.Vector3.Zero();
  48908. }
  48909. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48910. // In case the direction is present.
  48911. if (this.direction) {
  48912. if (!this.transformedDirection) {
  48913. this.transformedDirection = BABYLON.Vector3.Zero();
  48914. }
  48915. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48916. }
  48917. return true;
  48918. }
  48919. return false;
  48920. };
  48921. /**
  48922. * Return the depth scale used for the shadow map.
  48923. * @returns the depth scale.
  48924. */
  48925. ShadowLight.prototype.getDepthScale = function () {
  48926. return 50.0;
  48927. };
  48928. /**
  48929. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48930. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48931. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48932. */
  48933. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48934. return this.transformedDirection ? this.transformedDirection : this.direction;
  48935. };
  48936. /**
  48937. * Returns the ShadowLight absolute position in the World.
  48938. * @returns the position vector in world space
  48939. */
  48940. ShadowLight.prototype.getAbsolutePosition = function () {
  48941. return this.transformedPosition ? this.transformedPosition : this.position;
  48942. };
  48943. /**
  48944. * Sets the ShadowLight direction toward the passed target.
  48945. * @param target The point tot target in local space
  48946. * @returns the updated ShadowLight direction
  48947. */
  48948. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48949. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48950. return this.direction;
  48951. };
  48952. /**
  48953. * Returns the light rotation in euler definition.
  48954. * @returns the x y z rotation in local space.
  48955. */
  48956. ShadowLight.prototype.getRotation = function () {
  48957. this.direction.normalize();
  48958. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48959. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48960. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48961. };
  48962. /**
  48963. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48964. * @returns true if a cube texture needs to be use
  48965. */
  48966. ShadowLight.prototype.needCube = function () {
  48967. return false;
  48968. };
  48969. /**
  48970. * Detects if the projection matrix requires to be recomputed this frame.
  48971. * @returns true if it requires to be recomputed otherwise, false.
  48972. */
  48973. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48974. return this._needProjectionMatrixCompute;
  48975. };
  48976. /**
  48977. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48978. */
  48979. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48980. this._needProjectionMatrixCompute = true;
  48981. };
  48982. /**
  48983. * Get the world matrix of the sahdow lights.
  48984. * @hidden Internal Use Only
  48985. */
  48986. ShadowLight.prototype._getWorldMatrix = function () {
  48987. if (!this._worldMatrix) {
  48988. this._worldMatrix = BABYLON.Matrix.Identity();
  48989. }
  48990. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48991. return this._worldMatrix;
  48992. };
  48993. /**
  48994. * Gets the minZ used for shadow according to both the scene and the light.
  48995. * @param activeCamera The camera we are returning the min for
  48996. * @returns the depth min z
  48997. */
  48998. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48999. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49000. };
  49001. /**
  49002. * Gets the maxZ used for shadow according to both the scene and the light.
  49003. * @param activeCamera The camera we are returning the max for
  49004. * @returns the depth max z
  49005. */
  49006. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49007. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49008. };
  49009. /**
  49010. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49011. * @param matrix The materix to updated with the projection information
  49012. * @param viewMatrix The transform matrix of the light
  49013. * @param renderList The list of mesh to render in the map
  49014. * @returns The current light
  49015. */
  49016. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49017. if (this.customProjectionMatrixBuilder) {
  49018. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49019. }
  49020. else {
  49021. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49022. }
  49023. return this;
  49024. };
  49025. __decorate([
  49026. BABYLON.serializeAsVector3()
  49027. ], ShadowLight.prototype, "position", null);
  49028. __decorate([
  49029. BABYLON.serializeAsVector3()
  49030. ], ShadowLight.prototype, "direction", null);
  49031. __decorate([
  49032. BABYLON.serialize()
  49033. ], ShadowLight.prototype, "shadowMinZ", null);
  49034. __decorate([
  49035. BABYLON.serialize()
  49036. ], ShadowLight.prototype, "shadowMaxZ", null);
  49037. return ShadowLight;
  49038. }(BABYLON.Light));
  49039. BABYLON.ShadowLight = ShadowLight;
  49040. })(BABYLON || (BABYLON = {}));
  49041. //# sourceMappingURL=babylon.shadowLight.js.map
  49042. var BABYLON;
  49043. (function (BABYLON) {
  49044. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  49045. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  49046. });
  49047. /**
  49048. * A point light is a light defined by an unique point in world space.
  49049. * The light is emitted in every direction from this point.
  49050. * A good example of a point light is a standard light bulb.
  49051. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49052. */
  49053. var PointLight = /** @class */ (function (_super) {
  49054. __extends(PointLight, _super);
  49055. /**
  49056. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49057. * A PointLight emits the light in every direction.
  49058. * It can cast shadows.
  49059. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49060. * ```javascript
  49061. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49062. * ```
  49063. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49064. * @param name The light friendly name
  49065. * @param position The position of the point light in the scene
  49066. * @param scene The scene the lights belongs to
  49067. */
  49068. function PointLight(name, position, scene) {
  49069. var _this = _super.call(this, name, scene) || this;
  49070. _this._shadowAngle = Math.PI / 2;
  49071. _this.position = position;
  49072. return _this;
  49073. }
  49074. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49075. /**
  49076. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49077. * This specifies what angle the shadow will use to be created.
  49078. *
  49079. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49080. */
  49081. get: function () {
  49082. return this._shadowAngle;
  49083. },
  49084. /**
  49085. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49086. * This specifies what angle the shadow will use to be created.
  49087. *
  49088. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49089. */
  49090. set: function (value) {
  49091. this._shadowAngle = value;
  49092. this.forceProjectionMatrixCompute();
  49093. },
  49094. enumerable: true,
  49095. configurable: true
  49096. });
  49097. Object.defineProperty(PointLight.prototype, "direction", {
  49098. /**
  49099. * Gets the direction if it has been set.
  49100. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49101. */
  49102. get: function () {
  49103. return this._direction;
  49104. },
  49105. /**
  49106. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49107. */
  49108. set: function (value) {
  49109. var previousNeedCube = this.needCube();
  49110. this._direction = value;
  49111. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49112. this._shadowGenerator.recreateShadowMap();
  49113. }
  49114. },
  49115. enumerable: true,
  49116. configurable: true
  49117. });
  49118. /**
  49119. * Returns the string "PointLight"
  49120. * @returns the class name
  49121. */
  49122. PointLight.prototype.getClassName = function () {
  49123. return "PointLight";
  49124. };
  49125. /**
  49126. * Returns the integer 0.
  49127. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49128. */
  49129. PointLight.prototype.getTypeID = function () {
  49130. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49131. };
  49132. /**
  49133. * Specifies wether or not the shadowmap should be a cube texture.
  49134. * @returns true if the shadowmap needs to be a cube texture.
  49135. */
  49136. PointLight.prototype.needCube = function () {
  49137. return !this.direction;
  49138. };
  49139. /**
  49140. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49141. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49142. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49143. */
  49144. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49145. if (this.direction) {
  49146. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49147. }
  49148. else {
  49149. switch (faceIndex) {
  49150. case 0:
  49151. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49152. case 1:
  49153. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49154. case 2:
  49155. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49156. case 3:
  49157. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49158. case 4:
  49159. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49160. case 5:
  49161. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49162. }
  49163. }
  49164. return BABYLON.Vector3.Zero();
  49165. };
  49166. /**
  49167. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49168. * - fov = PI / 2
  49169. * - aspect ratio : 1.0
  49170. * - z-near and far equal to the active camera minZ and maxZ.
  49171. * Returns the PointLight.
  49172. */
  49173. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49174. var activeCamera = this.getScene().activeCamera;
  49175. if (!activeCamera) {
  49176. return;
  49177. }
  49178. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49179. };
  49180. PointLight.prototype._buildUniformLayout = function () {
  49181. this._uniformBuffer.addUniform("vLightData", 4);
  49182. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49183. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49184. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49185. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49186. this._uniformBuffer.addUniform("depthValues", 2);
  49187. this._uniformBuffer.create();
  49188. };
  49189. /**
  49190. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49191. * @param effect The effect to update
  49192. * @param lightIndex The index of the light in the effect to update
  49193. * @returns The point light
  49194. */
  49195. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49196. if (this.computeTransformedInformation()) {
  49197. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49198. }
  49199. else {
  49200. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49201. }
  49202. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  49203. return this;
  49204. };
  49205. /**
  49206. * Prepares the list of defines specific to the light type.
  49207. * @param defines the list of defines
  49208. * @param lightIndex defines the index of the light for the effect
  49209. */
  49210. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49211. defines["POINTLIGHT" + lightIndex] = true;
  49212. };
  49213. __decorate([
  49214. BABYLON.serialize()
  49215. ], PointLight.prototype, "shadowAngle", null);
  49216. return PointLight;
  49217. }(BABYLON.ShadowLight));
  49218. BABYLON.PointLight = PointLight;
  49219. })(BABYLON || (BABYLON = {}));
  49220. //# sourceMappingURL=babylon.pointLight.js.map
  49221. var BABYLON;
  49222. (function (BABYLON) {
  49223. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  49224. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  49225. });
  49226. /**
  49227. * A directional light is defined by a direction (what a surprise!).
  49228. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49229. * 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.
  49230. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49231. */
  49232. var DirectionalLight = /** @class */ (function (_super) {
  49233. __extends(DirectionalLight, _super);
  49234. /**
  49235. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49236. * The directional light is emitted from everywhere in the given direction.
  49237. * It can cast shawdows.
  49238. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49239. * @param name The friendly name of the light
  49240. * @param direction The direction of the light
  49241. * @param scene The scene the light belongs to
  49242. */
  49243. function DirectionalLight(name, direction, scene) {
  49244. var _this = _super.call(this, name, scene) || this;
  49245. _this._shadowFrustumSize = 0;
  49246. _this._shadowOrthoScale = 0.1;
  49247. /**
  49248. * Automatically compute the projection matrix to best fit (including all the casters)
  49249. * on each frame.
  49250. */
  49251. _this.autoUpdateExtends = true;
  49252. // Cache
  49253. _this._orthoLeft = Number.MAX_VALUE;
  49254. _this._orthoRight = Number.MIN_VALUE;
  49255. _this._orthoTop = Number.MIN_VALUE;
  49256. _this._orthoBottom = Number.MAX_VALUE;
  49257. _this.position = direction.scale(-1.0);
  49258. _this.direction = direction;
  49259. return _this;
  49260. }
  49261. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49262. /**
  49263. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49264. */
  49265. get: function () {
  49266. return this._shadowFrustumSize;
  49267. },
  49268. /**
  49269. * Specifies a fix frustum size for the shadow generation.
  49270. */
  49271. set: function (value) {
  49272. this._shadowFrustumSize = value;
  49273. this.forceProjectionMatrixCompute();
  49274. },
  49275. enumerable: true,
  49276. configurable: true
  49277. });
  49278. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49279. /**
  49280. * Gets the shadow projection scale against the optimal computed one.
  49281. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49282. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49283. */
  49284. get: function () {
  49285. return this._shadowOrthoScale;
  49286. },
  49287. /**
  49288. * Sets the shadow projection scale against the optimal computed one.
  49289. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49290. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49291. */
  49292. set: function (value) {
  49293. this._shadowOrthoScale = value;
  49294. this.forceProjectionMatrixCompute();
  49295. },
  49296. enumerable: true,
  49297. configurable: true
  49298. });
  49299. /**
  49300. * Returns the string "DirectionalLight".
  49301. * @return The class name
  49302. */
  49303. DirectionalLight.prototype.getClassName = function () {
  49304. return "DirectionalLight";
  49305. };
  49306. /**
  49307. * Returns the integer 1.
  49308. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49309. */
  49310. DirectionalLight.prototype.getTypeID = function () {
  49311. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49312. };
  49313. /**
  49314. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49315. * Returns the DirectionalLight Shadow projection matrix.
  49316. */
  49317. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49318. if (this.shadowFrustumSize > 0) {
  49319. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49320. }
  49321. else {
  49322. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49323. }
  49324. };
  49325. /**
  49326. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49327. * Returns the DirectionalLight Shadow projection matrix.
  49328. */
  49329. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49330. var activeCamera = this.getScene().activeCamera;
  49331. if (!activeCamera) {
  49332. return;
  49333. }
  49334. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49335. };
  49336. /**
  49337. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49338. * Returns the DirectionalLight Shadow projection matrix.
  49339. */
  49340. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49341. var activeCamera = this.getScene().activeCamera;
  49342. if (!activeCamera) {
  49343. return;
  49344. }
  49345. // Check extends
  49346. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49347. var tempVector3 = BABYLON.Vector3.Zero();
  49348. this._orthoLeft = Number.MAX_VALUE;
  49349. this._orthoRight = Number.MIN_VALUE;
  49350. this._orthoTop = Number.MIN_VALUE;
  49351. this._orthoBottom = Number.MAX_VALUE;
  49352. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49353. var mesh = renderList[meshIndex];
  49354. if (!mesh) {
  49355. continue;
  49356. }
  49357. var boundingInfo = mesh.getBoundingInfo();
  49358. var boundingBox = boundingInfo.boundingBox;
  49359. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49360. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49361. if (tempVector3.x < this._orthoLeft)
  49362. this._orthoLeft = tempVector3.x;
  49363. if (tempVector3.y < this._orthoBottom)
  49364. this._orthoBottom = tempVector3.y;
  49365. if (tempVector3.x > this._orthoRight)
  49366. this._orthoRight = tempVector3.x;
  49367. if (tempVector3.y > this._orthoTop)
  49368. this._orthoTop = tempVector3.y;
  49369. }
  49370. }
  49371. }
  49372. var xOffset = this._orthoRight - this._orthoLeft;
  49373. var yOffset = this._orthoTop - this._orthoBottom;
  49374. 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);
  49375. };
  49376. DirectionalLight.prototype._buildUniformLayout = function () {
  49377. this._uniformBuffer.addUniform("vLightData", 4);
  49378. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49379. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49380. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49381. this._uniformBuffer.addUniform("depthValues", 2);
  49382. this._uniformBuffer.create();
  49383. };
  49384. /**
  49385. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49386. * @param effect The effect to update
  49387. * @param lightIndex The index of the light in the effect to update
  49388. * @returns The directional light
  49389. */
  49390. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49391. if (this.computeTransformedInformation()) {
  49392. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49393. return this;
  49394. }
  49395. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49396. return this;
  49397. };
  49398. /**
  49399. * Gets the minZ used for shadow according to both the scene and the light.
  49400. *
  49401. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49402. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49403. * @param activeCamera The camera we are returning the min for
  49404. * @returns the depth min z
  49405. */
  49406. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49407. return 1;
  49408. };
  49409. /**
  49410. * Gets the maxZ used for shadow according to both the scene and the light.
  49411. *
  49412. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49413. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49414. * @param activeCamera The camera we are returning the max for
  49415. * @returns the depth max z
  49416. */
  49417. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49418. return 1;
  49419. };
  49420. /**
  49421. * Prepares the list of defines specific to the light type.
  49422. * @param defines the list of defines
  49423. * @param lightIndex defines the index of the light for the effect
  49424. */
  49425. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49426. defines["DIRLIGHT" + lightIndex] = true;
  49427. };
  49428. __decorate([
  49429. BABYLON.serialize()
  49430. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49431. __decorate([
  49432. BABYLON.serialize()
  49433. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49434. __decorate([
  49435. BABYLON.serialize()
  49436. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49437. return DirectionalLight;
  49438. }(BABYLON.ShadowLight));
  49439. BABYLON.DirectionalLight = DirectionalLight;
  49440. })(BABYLON || (BABYLON = {}));
  49441. //# sourceMappingURL=babylon.directionalLight.js.map
  49442. var BABYLON;
  49443. (function (BABYLON) {
  49444. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  49445. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  49446. });
  49447. /**
  49448. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49449. * These values define a cone of light starting from the position, emitting toward the direction.
  49450. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49451. * and the exponent defines the speed of the decay of the light with distance (reach).
  49452. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49453. */
  49454. var SpotLight = /** @class */ (function (_super) {
  49455. __extends(SpotLight, _super);
  49456. /**
  49457. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49458. * It can cast shadows.
  49459. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49460. * @param name The light friendly name
  49461. * @param position The position of the spot light in the scene
  49462. * @param direction The direction of the light in the scene
  49463. * @param angle The cone angle of the light in Radians
  49464. * @param exponent The light decay speed with the distance from the emission spot
  49465. * @param scene The scene the lights belongs to
  49466. */
  49467. function SpotLight(name, position, direction, angle, exponent, scene) {
  49468. var _this = _super.call(this, name, scene) || this;
  49469. _this._innerAngle = 0;
  49470. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49471. _this._projectionTextureLightNear = 1e-6;
  49472. _this._projectionTextureLightFar = 1000.0;
  49473. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49474. _this._projectionTextureViewLightDirty = true;
  49475. _this._projectionTextureProjectionLightDirty = true;
  49476. _this._projectionTextureDirty = true;
  49477. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49478. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49479. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49480. _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);
  49481. _this.position = position;
  49482. _this.direction = direction;
  49483. _this.angle = angle;
  49484. _this.exponent = exponent;
  49485. return _this;
  49486. }
  49487. Object.defineProperty(SpotLight.prototype, "angle", {
  49488. /**
  49489. * Gets the cone angle of the spot light in Radians.
  49490. */
  49491. get: function () {
  49492. return this._angle;
  49493. },
  49494. /**
  49495. * Sets the cone angle of the spot light in Radians.
  49496. */
  49497. set: function (value) {
  49498. this._angle = value;
  49499. this._cosHalfAngle = Math.cos(value * 0.5);
  49500. this._projectionTextureProjectionLightDirty = true;
  49501. this.forceProjectionMatrixCompute();
  49502. this._computeAngleValues();
  49503. },
  49504. enumerable: true,
  49505. configurable: true
  49506. });
  49507. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  49508. /**
  49509. * Only used in gltf falloff mode, this defines the angle where
  49510. * the directional falloff will start before cutting at angle which could be seen
  49511. * as outer angle.
  49512. */
  49513. get: function () {
  49514. return this._angle;
  49515. },
  49516. /**
  49517. * Only used in gltf falloff mode, this defines the angle where
  49518. * the directional falloff will start before cutting at angle which could be seen
  49519. * as outer angle.
  49520. */
  49521. set: function (value) {
  49522. this._innerAngle = value;
  49523. this._computeAngleValues();
  49524. },
  49525. enumerable: true,
  49526. configurable: true
  49527. });
  49528. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49529. /**
  49530. * Allows scaling the angle of the light for shadow generation only.
  49531. */
  49532. get: function () {
  49533. return this._shadowAngleScale;
  49534. },
  49535. /**
  49536. * Allows scaling the angle of the light for shadow generation only.
  49537. */
  49538. set: function (value) {
  49539. this._shadowAngleScale = value;
  49540. this.forceProjectionMatrixCompute();
  49541. },
  49542. enumerable: true,
  49543. configurable: true
  49544. });
  49545. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49546. /**
  49547. * Allows reading the projecton texture
  49548. */
  49549. get: function () {
  49550. return this._projectionTextureMatrix;
  49551. },
  49552. enumerable: true,
  49553. configurable: true
  49554. });
  49555. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49556. /**
  49557. * Gets the near clip of the Spotlight for texture projection.
  49558. */
  49559. get: function () {
  49560. return this._projectionTextureLightNear;
  49561. },
  49562. /**
  49563. * Sets the near clip of the Spotlight for texture projection.
  49564. */
  49565. set: function (value) {
  49566. this._projectionTextureLightNear = value;
  49567. this._projectionTextureProjectionLightDirty = true;
  49568. },
  49569. enumerable: true,
  49570. configurable: true
  49571. });
  49572. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49573. /**
  49574. * Gets the far clip of the Spotlight for texture projection.
  49575. */
  49576. get: function () {
  49577. return this._projectionTextureLightFar;
  49578. },
  49579. /**
  49580. * Sets the far clip of the Spotlight for texture projection.
  49581. */
  49582. set: function (value) {
  49583. this._projectionTextureLightFar = value;
  49584. this._projectionTextureProjectionLightDirty = true;
  49585. },
  49586. enumerable: true,
  49587. configurable: true
  49588. });
  49589. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49590. /**
  49591. * Gets the Up vector of the Spotlight for texture projection.
  49592. */
  49593. get: function () {
  49594. return this._projectionTextureUpDirection;
  49595. },
  49596. /**
  49597. * Sets the Up vector of the Spotlight for texture projection.
  49598. */
  49599. set: function (value) {
  49600. this._projectionTextureUpDirection = value;
  49601. this._projectionTextureProjectionLightDirty = true;
  49602. },
  49603. enumerable: true,
  49604. configurable: true
  49605. });
  49606. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49607. /**
  49608. * Gets the projection texture of the light.
  49609. */
  49610. get: function () {
  49611. return this._projectionTexture;
  49612. },
  49613. /**
  49614. * Sets the projection texture of the light.
  49615. */
  49616. set: function (value) {
  49617. this._projectionTexture = value;
  49618. this._projectionTextureDirty = true;
  49619. },
  49620. enumerable: true,
  49621. configurable: true
  49622. });
  49623. /**
  49624. * Returns the string "SpotLight".
  49625. * @returns the class name
  49626. */
  49627. SpotLight.prototype.getClassName = function () {
  49628. return "SpotLight";
  49629. };
  49630. /**
  49631. * Returns the integer 2.
  49632. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49633. */
  49634. SpotLight.prototype.getTypeID = function () {
  49635. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49636. };
  49637. /**
  49638. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49639. */
  49640. SpotLight.prototype._setDirection = function (value) {
  49641. _super.prototype._setDirection.call(this, value);
  49642. this._projectionTextureViewLightDirty = true;
  49643. };
  49644. /**
  49645. * Overrides the position setter to recompute the projection texture view light Matrix.
  49646. */
  49647. SpotLight.prototype._setPosition = function (value) {
  49648. _super.prototype._setPosition.call(this, value);
  49649. this._projectionTextureViewLightDirty = true;
  49650. };
  49651. /**
  49652. * 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.
  49653. * Returns the SpotLight.
  49654. */
  49655. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49656. var activeCamera = this.getScene().activeCamera;
  49657. if (!activeCamera) {
  49658. return;
  49659. }
  49660. this._shadowAngleScale = this._shadowAngleScale || 1;
  49661. var angle = this._shadowAngleScale * this._angle;
  49662. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49663. };
  49664. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49665. this._projectionTextureViewLightDirty = false;
  49666. this._projectionTextureDirty = true;
  49667. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49668. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49669. };
  49670. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49671. this._projectionTextureProjectionLightDirty = false;
  49672. this._projectionTextureDirty = true;
  49673. var light_far = this.projectionTextureLightFar;
  49674. var light_near = this.projectionTextureLightNear;
  49675. var P = light_far / (light_far - light_near);
  49676. var Q = -P * light_near;
  49677. var S = 1.0 / Math.tan(this._angle / 2.0);
  49678. var A = 1.0;
  49679. 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);
  49680. };
  49681. /**
  49682. * Main function for light texture projection matrix computing.
  49683. */
  49684. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49685. this._projectionTextureDirty = false;
  49686. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49687. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49688. };
  49689. SpotLight.prototype._buildUniformLayout = function () {
  49690. this._uniformBuffer.addUniform("vLightData", 4);
  49691. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49692. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49693. this._uniformBuffer.addUniform("vLightDirection", 3);
  49694. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49695. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49696. this._uniformBuffer.addUniform("depthValues", 2);
  49697. this._uniformBuffer.create();
  49698. };
  49699. SpotLight.prototype._computeAngleValues = function () {
  49700. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  49701. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  49702. };
  49703. /**
  49704. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49705. * @param effect The effect to update
  49706. * @param lightIndex The index of the light in the effect to update
  49707. * @returns The spot light
  49708. */
  49709. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49710. var normalizeDirection;
  49711. if (this.computeTransformedInformation()) {
  49712. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49713. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49714. }
  49715. else {
  49716. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49717. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49718. }
  49719. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  49720. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  49721. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49722. if (this._projectionTextureViewLightDirty) {
  49723. this._computeProjectionTextureViewLightMatrix();
  49724. }
  49725. if (this._projectionTextureProjectionLightDirty) {
  49726. this._computeProjectionTextureProjectionLightMatrix();
  49727. }
  49728. if (this._projectionTextureDirty) {
  49729. this._computeProjectionTextureMatrix();
  49730. }
  49731. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49732. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49733. }
  49734. return this;
  49735. };
  49736. /**
  49737. * Disposes the light and the associated resources.
  49738. */
  49739. SpotLight.prototype.dispose = function () {
  49740. _super.prototype.dispose.call(this);
  49741. if (this._projectionTexture) {
  49742. this._projectionTexture.dispose();
  49743. }
  49744. };
  49745. /**
  49746. * Prepares the list of defines specific to the light type.
  49747. * @param defines the list of defines
  49748. * @param lightIndex defines the index of the light for the effect
  49749. */
  49750. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49751. defines["SPOTLIGHT" + lightIndex] = true;
  49752. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49753. };
  49754. __decorate([
  49755. BABYLON.serialize()
  49756. ], SpotLight.prototype, "angle", null);
  49757. __decorate([
  49758. BABYLON.serialize()
  49759. ], SpotLight.prototype, "innerAngle", null);
  49760. __decorate([
  49761. BABYLON.serialize()
  49762. ], SpotLight.prototype, "shadowAngleScale", null);
  49763. __decorate([
  49764. BABYLON.serialize()
  49765. ], SpotLight.prototype, "exponent", void 0);
  49766. __decorate([
  49767. BABYLON.serialize()
  49768. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49769. __decorate([
  49770. BABYLON.serialize()
  49771. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49772. __decorate([
  49773. BABYLON.serialize()
  49774. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49775. __decorate([
  49776. BABYLON.serializeAsTexture("projectedLightTexture")
  49777. ], SpotLight.prototype, "_projectionTexture", void 0);
  49778. return SpotLight;
  49779. }(BABYLON.ShadowLight));
  49780. BABYLON.SpotLight = SpotLight;
  49781. })(BABYLON || (BABYLON = {}));
  49782. //# sourceMappingURL=babylon.spotLight.js.map
  49783. var BABYLON;
  49784. (function (BABYLON) {
  49785. /**
  49786. * Class used to override all child animations of a given target
  49787. */
  49788. var AnimationPropertiesOverride = /** @class */ (function () {
  49789. function AnimationPropertiesOverride() {
  49790. /**
  49791. * Gets or sets a value indicating if animation blending must be used
  49792. */
  49793. this.enableBlending = false;
  49794. /**
  49795. * Gets or sets the blending speed to use when enableBlending is true
  49796. */
  49797. this.blendingSpeed = 0.01;
  49798. /**
  49799. * Gets or sets the default loop mode to use
  49800. */
  49801. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49802. }
  49803. return AnimationPropertiesOverride;
  49804. }());
  49805. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49806. })(BABYLON || (BABYLON = {}));
  49807. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49808. var BABYLON;
  49809. (function (BABYLON) {
  49810. /**
  49811. * Represents the range of an animation
  49812. */
  49813. var AnimationRange = /** @class */ (function () {
  49814. /**
  49815. * Initializes the range of an animation
  49816. * @param name The name of the animation range
  49817. * @param from The starting frame of the animation
  49818. * @param to The ending frame of the animation
  49819. */
  49820. function AnimationRange(
  49821. /**The name of the animation range**/
  49822. name,
  49823. /**The starting frame of the animation */
  49824. from,
  49825. /**The ending frame of the animation*/
  49826. to) {
  49827. this.name = name;
  49828. this.from = from;
  49829. this.to = to;
  49830. }
  49831. /**
  49832. * Makes a copy of the animation range
  49833. * @returns A copy of the animation range
  49834. */
  49835. AnimationRange.prototype.clone = function () {
  49836. return new AnimationRange(this.name, this.from, this.to);
  49837. };
  49838. return AnimationRange;
  49839. }());
  49840. BABYLON.AnimationRange = AnimationRange;
  49841. /**
  49842. * Composed of a frame, and an action function
  49843. */
  49844. var AnimationEvent = /** @class */ (function () {
  49845. /**
  49846. * Initializes the animation event
  49847. * @param frame The frame for which the event is triggered
  49848. * @param action The event to perform when triggered
  49849. * @param onlyOnce Specifies if the event should be triggered only once
  49850. */
  49851. function AnimationEvent(
  49852. /** The frame for which the event is triggered **/
  49853. frame,
  49854. /** The event to perform when triggered **/
  49855. action,
  49856. /** Specifies if the event should be triggered only once**/
  49857. onlyOnce) {
  49858. this.frame = frame;
  49859. this.action = action;
  49860. this.onlyOnce = onlyOnce;
  49861. /**
  49862. * Specifies if the animation event is done
  49863. */
  49864. this.isDone = false;
  49865. }
  49866. /** @hidden */
  49867. AnimationEvent.prototype._clone = function () {
  49868. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49869. };
  49870. return AnimationEvent;
  49871. }());
  49872. BABYLON.AnimationEvent = AnimationEvent;
  49873. /**
  49874. * A cursor which tracks a point on a path
  49875. */
  49876. var PathCursor = /** @class */ (function () {
  49877. /**
  49878. * Initializes the path cursor
  49879. * @param path The path to track
  49880. */
  49881. function PathCursor(path) {
  49882. this.path = path;
  49883. /**
  49884. * Stores path cursor callbacks for when an onchange event is triggered
  49885. */
  49886. this._onchange = new Array();
  49887. /**
  49888. * The value of the path cursor
  49889. */
  49890. this.value = 0;
  49891. /**
  49892. * The animation array of the path cursor
  49893. */
  49894. this.animations = new Array();
  49895. }
  49896. /**
  49897. * Gets the cursor point on the path
  49898. * @returns A point on the path cursor at the cursor location
  49899. */
  49900. PathCursor.prototype.getPoint = function () {
  49901. var point = this.path.getPointAtLengthPosition(this.value);
  49902. return new BABYLON.Vector3(point.x, 0, point.y);
  49903. };
  49904. /**
  49905. * Moves the cursor ahead by the step amount
  49906. * @param step The amount to move the cursor forward
  49907. * @returns This path cursor
  49908. */
  49909. PathCursor.prototype.moveAhead = function (step) {
  49910. if (step === void 0) { step = 0.002; }
  49911. this.move(step);
  49912. return this;
  49913. };
  49914. /**
  49915. * Moves the cursor behind by the step amount
  49916. * @param step The amount to move the cursor back
  49917. * @returns This path cursor
  49918. */
  49919. PathCursor.prototype.moveBack = function (step) {
  49920. if (step === void 0) { step = 0.002; }
  49921. this.move(-step);
  49922. return this;
  49923. };
  49924. /**
  49925. * Moves the cursor by the step amount
  49926. * If the step amount is greater than one, an exception is thrown
  49927. * @param step The amount to move the cursor
  49928. * @returns This path cursor
  49929. */
  49930. PathCursor.prototype.move = function (step) {
  49931. if (Math.abs(step) > 1) {
  49932. throw "step size should be less than 1.";
  49933. }
  49934. this.value += step;
  49935. this.ensureLimits();
  49936. this.raiseOnChange();
  49937. return this;
  49938. };
  49939. /**
  49940. * Ensures that the value is limited between zero and one
  49941. * @returns This path cursor
  49942. */
  49943. PathCursor.prototype.ensureLimits = function () {
  49944. while (this.value > 1) {
  49945. this.value -= 1;
  49946. }
  49947. while (this.value < 0) {
  49948. this.value += 1;
  49949. }
  49950. return this;
  49951. };
  49952. /**
  49953. * Runs onchange callbacks on change (used by the animation engine)
  49954. * @returns This path cursor
  49955. */
  49956. PathCursor.prototype.raiseOnChange = function () {
  49957. var _this = this;
  49958. this._onchange.forEach(function (f) { return f(_this); });
  49959. return this;
  49960. };
  49961. /**
  49962. * Executes a function on change
  49963. * @param f A path cursor onchange callback
  49964. * @returns This path cursor
  49965. */
  49966. PathCursor.prototype.onchange = function (f) {
  49967. this._onchange.push(f);
  49968. return this;
  49969. };
  49970. return PathCursor;
  49971. }());
  49972. BABYLON.PathCursor = PathCursor;
  49973. /**
  49974. * Enum for the animation key frame interpolation type
  49975. */
  49976. var AnimationKeyInterpolation;
  49977. (function (AnimationKeyInterpolation) {
  49978. /**
  49979. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49980. */
  49981. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49982. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49983. /**
  49984. * Class used to store any kind of animation
  49985. */
  49986. var Animation = /** @class */ (function () {
  49987. /**
  49988. * Initializes the animation
  49989. * @param name Name of the animation
  49990. * @param targetProperty Property to animate
  49991. * @param framePerSecond The frames per second of the animation
  49992. * @param dataType The data type of the animation
  49993. * @param loopMode The loop mode of the animation
  49994. * @param enableBlendings Specifies if blending should be enabled
  49995. */
  49996. function Animation(
  49997. /**Name of the animation */
  49998. name,
  49999. /**Property to animate */
  50000. targetProperty,
  50001. /**The frames per second of the animation */
  50002. framePerSecond,
  50003. /**The data type of the animation */
  50004. dataType,
  50005. /**The loop mode of the animation */
  50006. loopMode,
  50007. /**Specifies if blending should be enabled */
  50008. enableBlending) {
  50009. this.name = name;
  50010. this.targetProperty = targetProperty;
  50011. this.framePerSecond = framePerSecond;
  50012. this.dataType = dataType;
  50013. this.loopMode = loopMode;
  50014. this.enableBlending = enableBlending;
  50015. /**
  50016. * @hidden Internal use only
  50017. */
  50018. this._runtimeAnimations = new Array();
  50019. /**
  50020. * The set of event that will be linked to this animation
  50021. */
  50022. this._events = new Array();
  50023. /**
  50024. * Stores the blending speed of the animation
  50025. */
  50026. this.blendingSpeed = 0.01;
  50027. /**
  50028. * Stores the animation ranges for the animation
  50029. */
  50030. this._ranges = {};
  50031. this.targetPropertyPath = targetProperty.split(".");
  50032. this.dataType = dataType;
  50033. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50034. }
  50035. /**
  50036. * @hidden Internal use
  50037. */
  50038. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50039. var dataType = undefined;
  50040. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50041. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50042. }
  50043. else if (from instanceof BABYLON.Quaternion) {
  50044. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50045. }
  50046. else if (from instanceof BABYLON.Vector3) {
  50047. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50048. }
  50049. else if (from instanceof BABYLON.Vector2) {
  50050. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50051. }
  50052. else if (from instanceof BABYLON.Color3) {
  50053. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50054. }
  50055. else if (from instanceof BABYLON.Size) {
  50056. dataType = Animation.ANIMATIONTYPE_SIZE;
  50057. }
  50058. if (dataType == undefined) {
  50059. return null;
  50060. }
  50061. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50062. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50063. animation.setKeys(keys);
  50064. if (easingFunction !== undefined) {
  50065. animation.setEasingFunction(easingFunction);
  50066. }
  50067. return animation;
  50068. };
  50069. /**
  50070. * Sets up an animation
  50071. * @param property The property to animate
  50072. * @param animationType The animation type to apply
  50073. * @param framePerSecond The frames per second of the animation
  50074. * @param easingFunction The easing function used in the animation
  50075. * @returns The created animation
  50076. */
  50077. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50078. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50079. animation.setEasingFunction(easingFunction);
  50080. return animation;
  50081. };
  50082. /**
  50083. * Create and start an animation on a node
  50084. * @param name defines the name of the global animation that will be run on all nodes
  50085. * @param node defines the root node where the animation will take place
  50086. * @param targetProperty defines property to animate
  50087. * @param framePerSecond defines the number of frame per second yo use
  50088. * @param totalFrame defines the number of frames in total
  50089. * @param from defines the initial value
  50090. * @param to defines the final value
  50091. * @param loopMode defines which loop mode you want to use (off by default)
  50092. * @param easingFunction defines the easing function to use (linear by default)
  50093. * @param onAnimationEnd defines the callback to call when animation end
  50094. * @returns the animatable created for this animation
  50095. */
  50096. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50097. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50098. if (!animation) {
  50099. return null;
  50100. }
  50101. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50102. };
  50103. /**
  50104. * Create and start an animation on a node and its descendants
  50105. * @param name defines the name of the global animation that will be run on all nodes
  50106. * @param node defines the root node where the animation will take place
  50107. * @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
  50108. * @param targetProperty defines property to animate
  50109. * @param framePerSecond defines the number of frame per second to use
  50110. * @param totalFrame defines the number of frames in total
  50111. * @param from defines the initial value
  50112. * @param to defines the final value
  50113. * @param loopMode defines which loop mode you want to use (off by default)
  50114. * @param easingFunction defines the easing function to use (linear by default)
  50115. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50116. * @returns the list of animatables created for all nodes
  50117. * @example https://www.babylonjs-playground.com/#MH0VLI
  50118. */
  50119. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50120. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50121. if (!animation) {
  50122. return null;
  50123. }
  50124. var scene = node.getScene();
  50125. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50126. };
  50127. /**
  50128. * Creates a new animation, merges it with the existing animations and starts it
  50129. * @param name Name of the animation
  50130. * @param node Node which contains the scene that begins the animations
  50131. * @param targetProperty Specifies which property to animate
  50132. * @param framePerSecond The frames per second of the animation
  50133. * @param totalFrame The total number of frames
  50134. * @param from The frame at the beginning of the animation
  50135. * @param to The frame at the end of the animation
  50136. * @param loopMode Specifies the loop mode of the animation
  50137. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50138. * @param onAnimationEnd Callback to run once the animation is complete
  50139. * @returns Nullable animation
  50140. */
  50141. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50142. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50143. if (!animation) {
  50144. return null;
  50145. }
  50146. node.animations.push(animation);
  50147. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50148. };
  50149. /**
  50150. * Transition property of an host to the target Value
  50151. * @param property The property to transition
  50152. * @param targetValue The target Value of the property
  50153. * @param host The object where the property to animate belongs
  50154. * @param scene Scene used to run the animation
  50155. * @param frameRate Framerate (in frame/s) to use
  50156. * @param transition The transition type we want to use
  50157. * @param duration The duration of the animation, in milliseconds
  50158. * @param onAnimationEnd Callback trigger at the end of the animation
  50159. * @returns Nullable animation
  50160. */
  50161. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50162. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50163. if (duration <= 0) {
  50164. host[property] = targetValue;
  50165. if (onAnimationEnd) {
  50166. onAnimationEnd();
  50167. }
  50168. return null;
  50169. }
  50170. var endFrame = frameRate * (duration / 1000);
  50171. transition.setKeys([{
  50172. frame: 0,
  50173. value: host[property].clone ? host[property].clone() : host[property]
  50174. },
  50175. {
  50176. frame: endFrame,
  50177. value: targetValue
  50178. }]);
  50179. if (!host.animations) {
  50180. host.animations = [];
  50181. }
  50182. host.animations.push(transition);
  50183. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50184. animation.onAnimationEnd = onAnimationEnd;
  50185. return animation;
  50186. };
  50187. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50188. /**
  50189. * Return the array of runtime animations currently using this animation
  50190. */
  50191. get: function () {
  50192. return this._runtimeAnimations;
  50193. },
  50194. enumerable: true,
  50195. configurable: true
  50196. });
  50197. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50198. /**
  50199. * Specifies if any of the runtime animations are currently running
  50200. */
  50201. get: function () {
  50202. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50203. var runtimeAnimation = _a[_i];
  50204. if (!runtimeAnimation.isStopped) {
  50205. return true;
  50206. }
  50207. }
  50208. return false;
  50209. },
  50210. enumerable: true,
  50211. configurable: true
  50212. });
  50213. // Methods
  50214. /**
  50215. * Converts the animation to a string
  50216. * @param fullDetails support for multiple levels of logging within scene loading
  50217. * @returns String form of the animation
  50218. */
  50219. Animation.prototype.toString = function (fullDetails) {
  50220. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50221. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50222. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50223. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50224. if (fullDetails) {
  50225. ret += ", Ranges: {";
  50226. var first = true;
  50227. for (var name in this._ranges) {
  50228. if (first) {
  50229. ret += ", ";
  50230. first = false;
  50231. }
  50232. ret += name;
  50233. }
  50234. ret += "}";
  50235. }
  50236. return ret;
  50237. };
  50238. /**
  50239. * Add an event to this animation
  50240. * @param event Event to add
  50241. */
  50242. Animation.prototype.addEvent = function (event) {
  50243. this._events.push(event);
  50244. };
  50245. /**
  50246. * Remove all events found at the given frame
  50247. * @param frame The frame to remove events from
  50248. */
  50249. Animation.prototype.removeEvents = function (frame) {
  50250. for (var index = 0; index < this._events.length; index++) {
  50251. if (this._events[index].frame === frame) {
  50252. this._events.splice(index, 1);
  50253. index--;
  50254. }
  50255. }
  50256. };
  50257. /**
  50258. * Retrieves all the events from the animation
  50259. * @returns Events from the animation
  50260. */
  50261. Animation.prototype.getEvents = function () {
  50262. return this._events;
  50263. };
  50264. /**
  50265. * Creates an animation range
  50266. * @param name Name of the animation range
  50267. * @param from Starting frame of the animation range
  50268. * @param to Ending frame of the animation
  50269. */
  50270. Animation.prototype.createRange = function (name, from, to) {
  50271. // check name not already in use; could happen for bones after serialized
  50272. if (!this._ranges[name]) {
  50273. this._ranges[name] = new AnimationRange(name, from, to);
  50274. }
  50275. };
  50276. /**
  50277. * Deletes an animation range by name
  50278. * @param name Name of the animation range to delete
  50279. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50280. */
  50281. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50282. if (deleteFrames === void 0) { deleteFrames = true; }
  50283. var range = this._ranges[name];
  50284. if (!range) {
  50285. return;
  50286. }
  50287. if (deleteFrames) {
  50288. var from = range.from;
  50289. var to = range.to;
  50290. // this loop MUST go high to low for multiple splices to work
  50291. for (var key = this._keys.length - 1; key >= 0; key--) {
  50292. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50293. this._keys.splice(key, 1);
  50294. }
  50295. }
  50296. }
  50297. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50298. };
  50299. /**
  50300. * Gets the animation range by name, or null if not defined
  50301. * @param name Name of the animation range
  50302. * @returns Nullable animation range
  50303. */
  50304. Animation.prototype.getRange = function (name) {
  50305. return this._ranges[name];
  50306. };
  50307. /**
  50308. * Gets the key frames from the animation
  50309. * @returns The key frames of the animation
  50310. */
  50311. Animation.prototype.getKeys = function () {
  50312. return this._keys;
  50313. };
  50314. /**
  50315. * Gets the highest frame rate of the animation
  50316. * @returns Highest frame rate of the animation
  50317. */
  50318. Animation.prototype.getHighestFrame = function () {
  50319. var ret = 0;
  50320. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50321. if (ret < this._keys[key].frame) {
  50322. ret = this._keys[key].frame;
  50323. }
  50324. }
  50325. return ret;
  50326. };
  50327. /**
  50328. * Gets the easing function of the animation
  50329. * @returns Easing function of the animation
  50330. */
  50331. Animation.prototype.getEasingFunction = function () {
  50332. return this._easingFunction;
  50333. };
  50334. /**
  50335. * Sets the easing function of the animation
  50336. * @param easingFunction A custom mathematical formula for animation
  50337. */
  50338. Animation.prototype.setEasingFunction = function (easingFunction) {
  50339. this._easingFunction = easingFunction;
  50340. };
  50341. /**
  50342. * Interpolates a scalar linearly
  50343. * @param startValue Start value of the animation curve
  50344. * @param endValue End value of the animation curve
  50345. * @param gradient Scalar amount to interpolate
  50346. * @returns Interpolated scalar value
  50347. */
  50348. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50349. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50350. };
  50351. /**
  50352. * Interpolates a scalar cubically
  50353. * @param startValue Start value of the animation curve
  50354. * @param outTangent End tangent of the animation
  50355. * @param endValue End value of the animation curve
  50356. * @param inTangent Start tangent of the animation curve
  50357. * @param gradient Scalar amount to interpolate
  50358. * @returns Interpolated scalar value
  50359. */
  50360. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50361. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50362. };
  50363. /**
  50364. * Interpolates a quaternion using a spherical linear interpolation
  50365. * @param startValue Start value of the animation curve
  50366. * @param endValue End value of the animation curve
  50367. * @param gradient Scalar amount to interpolate
  50368. * @returns Interpolated quaternion value
  50369. */
  50370. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50371. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50372. };
  50373. /**
  50374. * Interpolates a quaternion cubically
  50375. * @param startValue Start value of the animation curve
  50376. * @param outTangent End tangent of the animation curve
  50377. * @param endValue End value of the animation curve
  50378. * @param inTangent Start tangent of the animation curve
  50379. * @param gradient Scalar amount to interpolate
  50380. * @returns Interpolated quaternion value
  50381. */
  50382. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50383. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50384. };
  50385. /**
  50386. * Interpolates a Vector3 linearl
  50387. * @param startValue Start value of the animation curve
  50388. * @param endValue End value of the animation curve
  50389. * @param gradient Scalar amount to interpolate
  50390. * @returns Interpolated scalar value
  50391. */
  50392. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50393. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50394. };
  50395. /**
  50396. * Interpolates a Vector3 cubically
  50397. * @param startValue Start value of the animation curve
  50398. * @param outTangent End tangent of the animation
  50399. * @param endValue End value of the animation curve
  50400. * @param inTangent Start tangent of the animation curve
  50401. * @param gradient Scalar amount to interpolate
  50402. * @returns InterpolatedVector3 value
  50403. */
  50404. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50405. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50406. };
  50407. /**
  50408. * Interpolates a Vector2 linearly
  50409. * @param startValue Start value of the animation curve
  50410. * @param endValue End value of the animation curve
  50411. * @param gradient Scalar amount to interpolate
  50412. * @returns Interpolated Vector2 value
  50413. */
  50414. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50415. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50416. };
  50417. /**
  50418. * Interpolates a Vector2 cubically
  50419. * @param startValue Start value of the animation curve
  50420. * @param outTangent End tangent of the animation
  50421. * @param endValue End value of the animation curve
  50422. * @param inTangent Start tangent of the animation curve
  50423. * @param gradient Scalar amount to interpolate
  50424. * @returns Interpolated Vector2 value
  50425. */
  50426. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50427. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50428. };
  50429. /**
  50430. * Interpolates a size linearly
  50431. * @param startValue Start value of the animation curve
  50432. * @param endValue End value of the animation curve
  50433. * @param gradient Scalar amount to interpolate
  50434. * @returns Interpolated Size value
  50435. */
  50436. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50437. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50438. };
  50439. /**
  50440. * Interpolates a Color3 linearly
  50441. * @param startValue Start value of the animation curve
  50442. * @param endValue End value of the animation curve
  50443. * @param gradient Scalar amount to interpolate
  50444. * @returns Interpolated Color3 value
  50445. */
  50446. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50447. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50448. };
  50449. /**
  50450. * @hidden Internal use only
  50451. */
  50452. Animation.prototype._getKeyValue = function (value) {
  50453. if (typeof value === "function") {
  50454. return value();
  50455. }
  50456. return value;
  50457. };
  50458. /**
  50459. * @hidden Internal use only
  50460. */
  50461. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50462. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50463. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50464. }
  50465. var keys = this.getKeys();
  50466. // Try to get a hash to find the right key
  50467. 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));
  50468. if (keys[startKeyIndex].frame >= currentFrame) {
  50469. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50470. startKeyIndex--;
  50471. }
  50472. }
  50473. for (var key = startKeyIndex; key < keys.length; key++) {
  50474. var endKey = keys[key + 1];
  50475. if (endKey.frame >= currentFrame) {
  50476. var startKey = keys[key];
  50477. var startValue = this._getKeyValue(startKey.value);
  50478. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50479. return startValue;
  50480. }
  50481. var endValue = this._getKeyValue(endKey.value);
  50482. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50483. var frameDelta = endKey.frame - startKey.frame;
  50484. // gradient : percent of currentFrame between the frame inf and the frame sup
  50485. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50486. // check for easingFunction and correction of gradient
  50487. var easingFunction = this.getEasingFunction();
  50488. if (easingFunction != null) {
  50489. gradient = easingFunction.ease(gradient);
  50490. }
  50491. switch (this.dataType) {
  50492. // Float
  50493. case Animation.ANIMATIONTYPE_FLOAT:
  50494. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50495. switch (loopMode) {
  50496. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50497. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50498. return floatValue;
  50499. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50500. return offsetValue * repeatCount + floatValue;
  50501. }
  50502. break;
  50503. // Quaternion
  50504. case Animation.ANIMATIONTYPE_QUATERNION:
  50505. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50506. switch (loopMode) {
  50507. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50508. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50509. return quatValue;
  50510. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50511. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50512. }
  50513. return quatValue;
  50514. // Vector3
  50515. case Animation.ANIMATIONTYPE_VECTOR3:
  50516. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50517. switch (loopMode) {
  50518. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50519. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50520. return vec3Value;
  50521. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50522. return vec3Value.add(offsetValue.scale(repeatCount));
  50523. }
  50524. // Vector2
  50525. case Animation.ANIMATIONTYPE_VECTOR2:
  50526. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50527. switch (loopMode) {
  50528. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50529. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50530. return vec2Value;
  50531. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50532. return vec2Value.add(offsetValue.scale(repeatCount));
  50533. }
  50534. // Size
  50535. case Animation.ANIMATIONTYPE_SIZE:
  50536. switch (loopMode) {
  50537. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50538. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50539. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50540. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50541. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50542. }
  50543. // Color3
  50544. case Animation.ANIMATIONTYPE_COLOR3:
  50545. switch (loopMode) {
  50546. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50547. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50548. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50549. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50550. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50551. }
  50552. // Matrix
  50553. case Animation.ANIMATIONTYPE_MATRIX:
  50554. switch (loopMode) {
  50555. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50556. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50557. if (Animation.AllowMatricesInterpolation) {
  50558. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50559. }
  50560. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50561. return startValue;
  50562. }
  50563. default:
  50564. break;
  50565. }
  50566. break;
  50567. }
  50568. }
  50569. return this._getKeyValue(keys[keys.length - 1].value);
  50570. };
  50571. /**
  50572. * Defines the function to use to interpolate matrices
  50573. * @param startValue defines the start matrix
  50574. * @param endValue defines the end matrix
  50575. * @param gradient defines the gradient between both matrices
  50576. * @param result defines an optional target matrix where to store the interpolation
  50577. * @returns the interpolated matrix
  50578. */
  50579. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50580. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50581. if (result) {
  50582. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50583. return result;
  50584. }
  50585. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50586. }
  50587. if (result) {
  50588. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50589. return result;
  50590. }
  50591. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50592. };
  50593. /**
  50594. * Makes a copy of the animation
  50595. * @returns Cloned animation
  50596. */
  50597. Animation.prototype.clone = function () {
  50598. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50599. clone.enableBlending = this.enableBlending;
  50600. clone.blendingSpeed = this.blendingSpeed;
  50601. if (this._keys) {
  50602. clone.setKeys(this._keys);
  50603. }
  50604. if (this._ranges) {
  50605. clone._ranges = {};
  50606. for (var name in this._ranges) {
  50607. var range = this._ranges[name];
  50608. if (!range) {
  50609. continue;
  50610. }
  50611. clone._ranges[name] = range.clone();
  50612. }
  50613. }
  50614. return clone;
  50615. };
  50616. /**
  50617. * Sets the key frames of the animation
  50618. * @param values The animation key frames to set
  50619. */
  50620. Animation.prototype.setKeys = function (values) {
  50621. this._keys = values.slice(0);
  50622. };
  50623. /**
  50624. * Serializes the animation to an object
  50625. * @returns Serialized object
  50626. */
  50627. Animation.prototype.serialize = function () {
  50628. var serializationObject = {};
  50629. serializationObject.name = this.name;
  50630. serializationObject.property = this.targetProperty;
  50631. serializationObject.framePerSecond = this.framePerSecond;
  50632. serializationObject.dataType = this.dataType;
  50633. serializationObject.loopBehavior = this.loopMode;
  50634. serializationObject.enableBlending = this.enableBlending;
  50635. serializationObject.blendingSpeed = this.blendingSpeed;
  50636. var dataType = this.dataType;
  50637. serializationObject.keys = [];
  50638. var keys = this.getKeys();
  50639. for (var index = 0; index < keys.length; index++) {
  50640. var animationKey = keys[index];
  50641. var key = {};
  50642. key.frame = animationKey.frame;
  50643. switch (dataType) {
  50644. case Animation.ANIMATIONTYPE_FLOAT:
  50645. key.values = [animationKey.value];
  50646. break;
  50647. case Animation.ANIMATIONTYPE_QUATERNION:
  50648. case Animation.ANIMATIONTYPE_MATRIX:
  50649. case Animation.ANIMATIONTYPE_VECTOR3:
  50650. case Animation.ANIMATIONTYPE_COLOR3:
  50651. key.values = animationKey.value.asArray();
  50652. break;
  50653. }
  50654. serializationObject.keys.push(key);
  50655. }
  50656. serializationObject.ranges = [];
  50657. for (var name in this._ranges) {
  50658. var source = this._ranges[name];
  50659. if (!source) {
  50660. continue;
  50661. }
  50662. var range = {};
  50663. range.name = name;
  50664. range.from = source.from;
  50665. range.to = source.to;
  50666. serializationObject.ranges.push(range);
  50667. }
  50668. return serializationObject;
  50669. };
  50670. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50671. /**
  50672. * Get the float animation type
  50673. */
  50674. get: function () {
  50675. return Animation._ANIMATIONTYPE_FLOAT;
  50676. },
  50677. enumerable: true,
  50678. configurable: true
  50679. });
  50680. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50681. /**
  50682. * Get the Vector3 animation type
  50683. */
  50684. get: function () {
  50685. return Animation._ANIMATIONTYPE_VECTOR3;
  50686. },
  50687. enumerable: true,
  50688. configurable: true
  50689. });
  50690. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50691. /**
  50692. * Get the Vector2 animation type
  50693. */
  50694. get: function () {
  50695. return Animation._ANIMATIONTYPE_VECTOR2;
  50696. },
  50697. enumerable: true,
  50698. configurable: true
  50699. });
  50700. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50701. /**
  50702. * Get the Size animation type
  50703. */
  50704. get: function () {
  50705. return Animation._ANIMATIONTYPE_SIZE;
  50706. },
  50707. enumerable: true,
  50708. configurable: true
  50709. });
  50710. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50711. /**
  50712. * Get the Quaternion animation type
  50713. */
  50714. get: function () {
  50715. return Animation._ANIMATIONTYPE_QUATERNION;
  50716. },
  50717. enumerable: true,
  50718. configurable: true
  50719. });
  50720. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50721. /**
  50722. * Get the Matrix animation type
  50723. */
  50724. get: function () {
  50725. return Animation._ANIMATIONTYPE_MATRIX;
  50726. },
  50727. enumerable: true,
  50728. configurable: true
  50729. });
  50730. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50731. /**
  50732. * Get the Color3 animation type
  50733. */
  50734. get: function () {
  50735. return Animation._ANIMATIONTYPE_COLOR3;
  50736. },
  50737. enumerable: true,
  50738. configurable: true
  50739. });
  50740. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50741. /**
  50742. * Get the Relative Loop Mode
  50743. */
  50744. get: function () {
  50745. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50746. },
  50747. enumerable: true,
  50748. configurable: true
  50749. });
  50750. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50751. /**
  50752. * Get the Cycle Loop Mode
  50753. */
  50754. get: function () {
  50755. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50756. },
  50757. enumerable: true,
  50758. configurable: true
  50759. });
  50760. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50761. /**
  50762. * Get the Constant Loop Mode
  50763. */
  50764. get: function () {
  50765. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50766. },
  50767. enumerable: true,
  50768. configurable: true
  50769. });
  50770. /** @hidden */
  50771. Animation._UniversalLerp = function (left, right, amount) {
  50772. var constructor = left.constructor;
  50773. if (constructor.Lerp) { // Lerp supported
  50774. return constructor.Lerp(left, right, amount);
  50775. }
  50776. else if (constructor.Slerp) { // Slerp supported
  50777. return constructor.Slerp(left, right, amount);
  50778. }
  50779. else if (left.toFixed) { // Number
  50780. return left * (1.0 - amount) + amount * right;
  50781. }
  50782. else { // Blending not supported
  50783. return right;
  50784. }
  50785. };
  50786. /**
  50787. * Parses an animation object and creates an animation
  50788. * @param parsedAnimation Parsed animation object
  50789. * @returns Animation object
  50790. */
  50791. Animation.Parse = function (parsedAnimation) {
  50792. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50793. var dataType = parsedAnimation.dataType;
  50794. var keys = [];
  50795. var data;
  50796. var index;
  50797. if (parsedAnimation.enableBlending) {
  50798. animation.enableBlending = parsedAnimation.enableBlending;
  50799. }
  50800. if (parsedAnimation.blendingSpeed) {
  50801. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50802. }
  50803. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50804. var key = parsedAnimation.keys[index];
  50805. var inTangent;
  50806. var outTangent;
  50807. switch (dataType) {
  50808. case Animation.ANIMATIONTYPE_FLOAT:
  50809. data = key.values[0];
  50810. if (key.values.length >= 1) {
  50811. inTangent = key.values[1];
  50812. }
  50813. if (key.values.length >= 2) {
  50814. outTangent = key.values[2];
  50815. }
  50816. break;
  50817. case Animation.ANIMATIONTYPE_QUATERNION:
  50818. data = BABYLON.Quaternion.FromArray(key.values);
  50819. if (key.values.length >= 8) {
  50820. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50821. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50822. inTangent = _inTangent;
  50823. }
  50824. }
  50825. if (key.values.length >= 12) {
  50826. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50827. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50828. outTangent = _outTangent;
  50829. }
  50830. }
  50831. break;
  50832. case Animation.ANIMATIONTYPE_MATRIX:
  50833. data = BABYLON.Matrix.FromArray(key.values);
  50834. break;
  50835. case Animation.ANIMATIONTYPE_COLOR3:
  50836. data = BABYLON.Color3.FromArray(key.values);
  50837. break;
  50838. case Animation.ANIMATIONTYPE_VECTOR3:
  50839. default:
  50840. data = BABYLON.Vector3.FromArray(key.values);
  50841. break;
  50842. }
  50843. var keyData = {};
  50844. keyData.frame = key.frame;
  50845. keyData.value = data;
  50846. if (inTangent != undefined) {
  50847. keyData.inTangent = inTangent;
  50848. }
  50849. if (outTangent != undefined) {
  50850. keyData.outTangent = outTangent;
  50851. }
  50852. keys.push(keyData);
  50853. }
  50854. animation.setKeys(keys);
  50855. if (parsedAnimation.ranges) {
  50856. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50857. data = parsedAnimation.ranges[index];
  50858. animation.createRange(data.name, data.from, data.to);
  50859. }
  50860. }
  50861. return animation;
  50862. };
  50863. /**
  50864. * Appends the serialized animations from the source animations
  50865. * @param source Source containing the animations
  50866. * @param destination Target to store the animations
  50867. */
  50868. Animation.AppendSerializedAnimations = function (source, destination) {
  50869. if (source.animations) {
  50870. destination.animations = [];
  50871. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50872. var animation = source.animations[animationIndex];
  50873. destination.animations.push(animation.serialize());
  50874. }
  50875. }
  50876. };
  50877. /**
  50878. * Use matrix interpolation instead of using direct key value when animating matrices
  50879. */
  50880. Animation.AllowMatricesInterpolation = false;
  50881. /**
  50882. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50883. */
  50884. Animation.AllowMatrixDecomposeForInterpolation = true;
  50885. // Statics
  50886. /**
  50887. * Float animation type
  50888. */
  50889. Animation._ANIMATIONTYPE_FLOAT = 0;
  50890. /**
  50891. * Vector3 animation type
  50892. */
  50893. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50894. /**
  50895. * Quaternion animation type
  50896. */
  50897. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50898. /**
  50899. * Matrix animation type
  50900. */
  50901. Animation._ANIMATIONTYPE_MATRIX = 3;
  50902. /**
  50903. * Color3 animation type
  50904. */
  50905. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50906. /**
  50907. * Vector2 animation type
  50908. */
  50909. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50910. /**
  50911. * Size animation type
  50912. */
  50913. Animation._ANIMATIONTYPE_SIZE = 6;
  50914. /**
  50915. * Relative Loop Mode
  50916. */
  50917. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50918. /**
  50919. * Cycle Loop Mode
  50920. */
  50921. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50922. /**
  50923. * Constant Loop Mode
  50924. */
  50925. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50926. return Animation;
  50927. }());
  50928. BABYLON.Animation = Animation;
  50929. })(BABYLON || (BABYLON = {}));
  50930. //# sourceMappingURL=babylon.animation.js.map
  50931. var BABYLON;
  50932. (function (BABYLON) {
  50933. /**
  50934. * This class defines the direct association between an animation and a target
  50935. */
  50936. var TargetedAnimation = /** @class */ (function () {
  50937. function TargetedAnimation() {
  50938. }
  50939. return TargetedAnimation;
  50940. }());
  50941. BABYLON.TargetedAnimation = TargetedAnimation;
  50942. /**
  50943. * Use this class to create coordinated animations on multiple targets
  50944. */
  50945. var AnimationGroup = /** @class */ (function () {
  50946. function AnimationGroup(name, scene) {
  50947. if (scene === void 0) { scene = null; }
  50948. this.name = name;
  50949. this._targetedAnimations = new Array();
  50950. this._animatables = new Array();
  50951. this._from = Number.MAX_VALUE;
  50952. this._to = -Number.MAX_VALUE;
  50953. this._speedRatio = 1;
  50954. this.onAnimationEndObservable = new BABYLON.Observable();
  50955. /**
  50956. * This observable will notify when all animations have ended.
  50957. */
  50958. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50959. /**
  50960. * This observable will notify when all animations have paused.
  50961. */
  50962. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  50963. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50964. this._scene.animationGroups.push(this);
  50965. }
  50966. Object.defineProperty(AnimationGroup.prototype, "from", {
  50967. /**
  50968. * Gets the first frame
  50969. */
  50970. get: function () {
  50971. return this._from;
  50972. },
  50973. enumerable: true,
  50974. configurable: true
  50975. });
  50976. Object.defineProperty(AnimationGroup.prototype, "to", {
  50977. /**
  50978. * Gets the last frame
  50979. */
  50980. get: function () {
  50981. return this._to;
  50982. },
  50983. enumerable: true,
  50984. configurable: true
  50985. });
  50986. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50987. /**
  50988. * Define if the animations are started
  50989. */
  50990. get: function () {
  50991. return this._isStarted;
  50992. },
  50993. enumerable: true,
  50994. configurable: true
  50995. });
  50996. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50997. /**
  50998. * Gets or sets the speed ratio to use for all animations
  50999. */
  51000. get: function () {
  51001. return this._speedRatio;
  51002. },
  51003. /**
  51004. * Gets or sets the speed ratio to use for all animations
  51005. */
  51006. set: function (value) {
  51007. if (this._speedRatio === value) {
  51008. return;
  51009. }
  51010. this._speedRatio = value;
  51011. for (var index = 0; index < this._animatables.length; index++) {
  51012. var animatable = this._animatables[index];
  51013. animatable.speedRatio = this._speedRatio;
  51014. }
  51015. },
  51016. enumerable: true,
  51017. configurable: true
  51018. });
  51019. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51020. /**
  51021. * Gets the targeted animations for this animation group
  51022. */
  51023. get: function () {
  51024. return this._targetedAnimations;
  51025. },
  51026. enumerable: true,
  51027. configurable: true
  51028. });
  51029. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51030. /**
  51031. * returning the list of animatables controlled by this animation group.
  51032. */
  51033. get: function () {
  51034. return this._animatables;
  51035. },
  51036. enumerable: true,
  51037. configurable: true
  51038. });
  51039. /**
  51040. * Add an animation (with its target) in the group
  51041. * @param animation defines the animation we want to add
  51042. * @param target defines the target of the animation
  51043. * @returns the {BABYLON.TargetedAnimation} object
  51044. */
  51045. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51046. var targetedAnimation = {
  51047. animation: animation,
  51048. target: target
  51049. };
  51050. var keys = animation.getKeys();
  51051. if (this._from > keys[0].frame) {
  51052. this._from = keys[0].frame;
  51053. }
  51054. if (this._to < keys[keys.length - 1].frame) {
  51055. this._to = keys[keys.length - 1].frame;
  51056. }
  51057. this._targetedAnimations.push(targetedAnimation);
  51058. return targetedAnimation;
  51059. };
  51060. /**
  51061. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51062. * It can add constant keys at begin or end
  51063. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51064. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51065. */
  51066. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51067. if (beginFrame === void 0) { beginFrame = null; }
  51068. if (endFrame === void 0) { endFrame = null; }
  51069. if (beginFrame == null)
  51070. beginFrame = this._from;
  51071. if (endFrame == null)
  51072. endFrame = this._to;
  51073. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51074. var targetedAnimation = this._targetedAnimations[index];
  51075. var keys = targetedAnimation.animation.getKeys();
  51076. var startKey = keys[0];
  51077. var endKey = keys[keys.length - 1];
  51078. if (startKey.frame > beginFrame) {
  51079. var newKey = {
  51080. frame: beginFrame,
  51081. value: startKey.value,
  51082. inTangent: startKey.inTangent,
  51083. outTangent: startKey.outTangent,
  51084. interpolation: startKey.interpolation
  51085. };
  51086. keys.splice(0, 0, newKey);
  51087. }
  51088. if (endKey.frame < endFrame) {
  51089. var newKey = {
  51090. frame: endFrame,
  51091. value: endKey.value,
  51092. inTangent: endKey.outTangent,
  51093. outTangent: endKey.outTangent,
  51094. interpolation: endKey.interpolation
  51095. };
  51096. keys.push(newKey);
  51097. }
  51098. }
  51099. this._from = beginFrame;
  51100. this._to = endFrame;
  51101. return this;
  51102. };
  51103. /**
  51104. * Start all animations on given targets
  51105. * @param loop defines if animations must loop
  51106. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51107. * @param from defines the from key (optional)
  51108. * @param to defines the to key (optional)
  51109. * @returns the current animation group
  51110. */
  51111. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51112. var _this = this;
  51113. if (loop === void 0) { loop = false; }
  51114. if (speedRatio === void 0) { speedRatio = 1; }
  51115. if (this._isStarted || this._targetedAnimations.length === 0) {
  51116. return this;
  51117. }
  51118. var _loop_1 = function (targetedAnimation) {
  51119. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51120. animatable.onAnimationEnd = function () {
  51121. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51122. _this._checkAnimationGroupEnded(animatable);
  51123. };
  51124. this_1._animatables.push(animatable);
  51125. };
  51126. var this_1 = this;
  51127. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51128. var targetedAnimation = _a[_i];
  51129. _loop_1(targetedAnimation);
  51130. }
  51131. this._speedRatio = speedRatio;
  51132. this._isStarted = true;
  51133. return this;
  51134. };
  51135. /**
  51136. * Pause all animations
  51137. */
  51138. AnimationGroup.prototype.pause = function () {
  51139. if (!this._isStarted) {
  51140. return this;
  51141. }
  51142. for (var index = 0; index < this._animatables.length; index++) {
  51143. var animatable = this._animatables[index];
  51144. animatable.pause();
  51145. }
  51146. this.onAnimationGroupPauseObservable.notifyObservers(this);
  51147. return this;
  51148. };
  51149. /**
  51150. * Play all animations to initial state
  51151. * This function will start() the animations if they were not started or will restart() them if they were paused
  51152. * @param loop defines if animations must loop
  51153. */
  51154. AnimationGroup.prototype.play = function (loop) {
  51155. // only if all animatables are ready and exist
  51156. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51157. if (loop !== undefined) {
  51158. for (var index = 0; index < this._animatables.length; index++) {
  51159. var animatable = this._animatables[index];
  51160. animatable.loopAnimation = loop;
  51161. }
  51162. }
  51163. this.restart();
  51164. }
  51165. else {
  51166. this.stop();
  51167. this.start(loop, this._speedRatio);
  51168. }
  51169. return this;
  51170. };
  51171. /**
  51172. * Reset all animations to initial state
  51173. */
  51174. AnimationGroup.prototype.reset = function () {
  51175. if (!this._isStarted) {
  51176. return this;
  51177. }
  51178. for (var index = 0; index < this._animatables.length; index++) {
  51179. var animatable = this._animatables[index];
  51180. animatable.reset();
  51181. }
  51182. return this;
  51183. };
  51184. /**
  51185. * Restart animations from key 0
  51186. */
  51187. AnimationGroup.prototype.restart = function () {
  51188. if (!this._isStarted) {
  51189. return this;
  51190. }
  51191. for (var index = 0; index < this._animatables.length; index++) {
  51192. var animatable = this._animatables[index];
  51193. animatable.restart();
  51194. }
  51195. return this;
  51196. };
  51197. /**
  51198. * Stop all animations
  51199. */
  51200. AnimationGroup.prototype.stop = function () {
  51201. if (!this._isStarted) {
  51202. return this;
  51203. }
  51204. var list = this._animatables.slice();
  51205. for (var index = 0; index < list.length; index++) {
  51206. list[index].stop();
  51207. }
  51208. this._isStarted = false;
  51209. return this;
  51210. };
  51211. /**
  51212. * Set animation weight for all animatables
  51213. * @param weight defines the weight to use
  51214. * @return the animationGroup
  51215. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51216. */
  51217. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51218. for (var index = 0; index < this._animatables.length; index++) {
  51219. var animatable = this._animatables[index];
  51220. animatable.weight = weight;
  51221. }
  51222. return this;
  51223. };
  51224. /**
  51225. * Synchronize and normalize all animatables with a source animatable
  51226. * @param root defines the root animatable to synchronize with
  51227. * @return the animationGroup
  51228. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51229. */
  51230. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51231. for (var index = 0; index < this._animatables.length; index++) {
  51232. var animatable = this._animatables[index];
  51233. animatable.syncWith(root);
  51234. }
  51235. return this;
  51236. };
  51237. /**
  51238. * Goes to a specific frame in this animation group
  51239. * @param frame the frame number to go to
  51240. * @return the animationGroup
  51241. */
  51242. AnimationGroup.prototype.goToFrame = function (frame) {
  51243. if (!this._isStarted) {
  51244. return this;
  51245. }
  51246. for (var index = 0; index < this._animatables.length; index++) {
  51247. var animatable = this._animatables[index];
  51248. animatable.goToFrame(frame);
  51249. }
  51250. return this;
  51251. };
  51252. /**
  51253. * Dispose all associated resources
  51254. */
  51255. AnimationGroup.prototype.dispose = function () {
  51256. this._targetedAnimations = [];
  51257. this._animatables = [];
  51258. var index = this._scene.animationGroups.indexOf(this);
  51259. if (index > -1) {
  51260. this._scene.animationGroups.splice(index, 1);
  51261. }
  51262. };
  51263. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  51264. // animatable should be taken out of the array
  51265. var idx = this._animatables.indexOf(animatable);
  51266. if (idx > -1) {
  51267. this._animatables.splice(idx, 1);
  51268. }
  51269. // all animatables were removed? animation group ended!
  51270. if (this._animatables.length === 0) {
  51271. this._isStarted = false;
  51272. this.onAnimationGroupEndObservable.notifyObservers(this);
  51273. }
  51274. };
  51275. return AnimationGroup;
  51276. }());
  51277. BABYLON.AnimationGroup = AnimationGroup;
  51278. })(BABYLON || (BABYLON = {}));
  51279. //# sourceMappingURL=babylon.animationGroup.js.map
  51280. var BABYLON;
  51281. (function (BABYLON) {
  51282. // Static values to help the garbage collector
  51283. // Quaternion
  51284. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  51285. // Vector3
  51286. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  51287. // Vector2
  51288. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  51289. // Size
  51290. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  51291. // Color3
  51292. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  51293. /**
  51294. * Defines a runtime animation
  51295. */
  51296. var RuntimeAnimation = /** @class */ (function () {
  51297. /**
  51298. * Create a new RuntimeAnimation object
  51299. * @param target defines the target of the animation
  51300. * @param animation defines the source animation object
  51301. * @param scene defines the hosting scene
  51302. * @param host defines the initiating Animatable
  51303. */
  51304. function RuntimeAnimation(target, animation, scene, host) {
  51305. var _this = this;
  51306. this._events = new Array();
  51307. /**
  51308. * The current frame of the runtime animation
  51309. */
  51310. this._currentFrame = 0;
  51311. /**
  51312. * The original value of the runtime animation
  51313. */
  51314. this._originalValue = new Array();
  51315. /**
  51316. * The offsets cache of the runtime animation
  51317. */
  51318. this._offsetsCache = {};
  51319. /**
  51320. * The high limits cache of the runtime animation
  51321. */
  51322. this._highLimitsCache = {};
  51323. /**
  51324. * Specifies if the runtime animation has been stopped
  51325. */
  51326. this._stopped = false;
  51327. /**
  51328. * The blending factor of the runtime animation
  51329. */
  51330. this._blendingFactor = 0;
  51331. /**
  51332. * The target path of the runtime animation
  51333. */
  51334. this._targetPath = "";
  51335. /**
  51336. * The weight of the runtime animation
  51337. */
  51338. this._weight = 1.0;
  51339. /**
  51340. * The ratio offset of the runtime animation
  51341. */
  51342. this._ratioOffset = 0;
  51343. /**
  51344. * The previous delay of the runtime animation
  51345. */
  51346. this._previousDelay = 0;
  51347. /**
  51348. * The previous ratio of the runtime animation
  51349. */
  51350. this._previousRatio = 0;
  51351. this._animation = animation;
  51352. this._target = target;
  51353. this._scene = scene;
  51354. this._host = host;
  51355. animation._runtimeAnimations.push(this);
  51356. // Cloning events locally
  51357. var events = animation.getEvents();
  51358. if (events && events.length > 0) {
  51359. events.forEach(function (e) {
  51360. _this._events.push(e._clone());
  51361. });
  51362. }
  51363. }
  51364. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51365. /**
  51366. * Gets the current frame of the runtime animation
  51367. */
  51368. get: function () {
  51369. return this._currentFrame;
  51370. },
  51371. enumerable: true,
  51372. configurable: true
  51373. });
  51374. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51375. /**
  51376. * Gets the weight of the runtime animation
  51377. */
  51378. get: function () {
  51379. return this._weight;
  51380. },
  51381. enumerable: true,
  51382. configurable: true
  51383. });
  51384. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51385. /**
  51386. * Gets the current value of the runtime animation
  51387. */
  51388. get: function () {
  51389. return this._currentValue;
  51390. },
  51391. enumerable: true,
  51392. configurable: true
  51393. });
  51394. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51395. /**
  51396. * Gets the target path of the runtime animation
  51397. */
  51398. get: function () {
  51399. return this._targetPath;
  51400. },
  51401. enumerable: true,
  51402. configurable: true
  51403. });
  51404. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51405. /**
  51406. * Gets the actual target of the runtime animation
  51407. */
  51408. get: function () {
  51409. return this._activeTarget;
  51410. },
  51411. enumerable: true,
  51412. configurable: true
  51413. });
  51414. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51415. /**
  51416. * Gets the animation from the runtime animation
  51417. */
  51418. get: function () {
  51419. return this._animation;
  51420. },
  51421. enumerable: true,
  51422. configurable: true
  51423. });
  51424. /**
  51425. * Resets the runtime animation to the beginning
  51426. * @param restoreOriginal defines whether to restore the target property to the original value
  51427. */
  51428. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51429. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51430. if (restoreOriginal) {
  51431. if (this._target instanceof Array) {
  51432. var index = 0;
  51433. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51434. var target = _a[_i];
  51435. if (this._originalValue[index] !== undefined) {
  51436. this._setValue(target, this._originalValue[index], -1);
  51437. }
  51438. index++;
  51439. }
  51440. }
  51441. else {
  51442. if (this._originalValue[0] !== undefined) {
  51443. this._setValue(this._target, this._originalValue[0], -1);
  51444. }
  51445. }
  51446. }
  51447. this._offsetsCache = {};
  51448. this._highLimitsCache = {};
  51449. this._currentFrame = 0;
  51450. this._blendingFactor = 0;
  51451. this._originalValue = new Array();
  51452. // Events
  51453. for (var index = 0; index < this._events.length; index++) {
  51454. this._events[index].isDone = false;
  51455. }
  51456. };
  51457. /**
  51458. * Specifies if the runtime animation is stopped
  51459. * @returns Boolean specifying if the runtime animation is stopped
  51460. */
  51461. RuntimeAnimation.prototype.isStopped = function () {
  51462. return this._stopped;
  51463. };
  51464. /**
  51465. * Disposes of the runtime animation
  51466. */
  51467. RuntimeAnimation.prototype.dispose = function () {
  51468. var index = this._animation.runtimeAnimations.indexOf(this);
  51469. if (index > -1) {
  51470. this._animation.runtimeAnimations.splice(index, 1);
  51471. }
  51472. };
  51473. /**
  51474. * Interpolates the animation from the current frame
  51475. * @param currentFrame The frame to interpolate the animation to
  51476. * @param repeatCount The number of times that the animation should loop
  51477. * @param loopMode The type of looping mode to use
  51478. * @param offsetValue Animation offset value
  51479. * @param highLimitValue The high limit value
  51480. * @returns The interpolated value
  51481. */
  51482. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51483. this._currentFrame = currentFrame;
  51484. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51485. this._workValue = BABYLON.Matrix.Zero();
  51486. }
  51487. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51488. };
  51489. /**
  51490. * Apply the interpolated value to the target
  51491. * @param currentValue defines the value computed by the animation
  51492. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51493. */
  51494. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51495. if (weight === void 0) { weight = 1.0; }
  51496. if (this._target instanceof Array) {
  51497. var index = 0;
  51498. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51499. var target = _a[_i];
  51500. this._setValue(target, currentValue, weight, index);
  51501. index++;
  51502. }
  51503. }
  51504. else {
  51505. this._setValue(this._target, currentValue, weight);
  51506. }
  51507. };
  51508. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51509. if (targetIndex === void 0) { targetIndex = 0; }
  51510. // Set value
  51511. var path;
  51512. var destination;
  51513. var targetPropertyPath = this._animation.targetPropertyPath;
  51514. if (targetPropertyPath.length > 1) {
  51515. var property = target[targetPropertyPath[0]];
  51516. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51517. property = property[targetPropertyPath[index]];
  51518. }
  51519. path = targetPropertyPath[targetPropertyPath.length - 1];
  51520. destination = property;
  51521. }
  51522. else {
  51523. path = targetPropertyPath[0];
  51524. destination = target;
  51525. }
  51526. this._targetPath = path;
  51527. this._activeTarget = destination;
  51528. this._weight = weight;
  51529. if (this._originalValue[targetIndex] === undefined) {
  51530. var originalValue = void 0;
  51531. if (destination.getRestPose && path === "_matrix") { // For bones
  51532. originalValue = destination.getRestPose();
  51533. }
  51534. else {
  51535. originalValue = destination[path];
  51536. }
  51537. if (originalValue && originalValue.clone) {
  51538. this._originalValue[targetIndex] = originalValue.clone();
  51539. }
  51540. else {
  51541. this._originalValue[targetIndex] = originalValue;
  51542. }
  51543. }
  51544. // Blending
  51545. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51546. if (enableBlending && this._blendingFactor <= 1.0) {
  51547. if (!this._originalBlendValue) {
  51548. var originalValue = destination[path];
  51549. if (originalValue.clone) {
  51550. this._originalBlendValue = originalValue.clone();
  51551. }
  51552. else {
  51553. this._originalBlendValue = originalValue;
  51554. }
  51555. }
  51556. if (this._originalBlendValue.m) { // Matrix
  51557. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51558. if (this._currentValue) {
  51559. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51560. }
  51561. else {
  51562. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51563. }
  51564. }
  51565. else {
  51566. if (this._currentValue) {
  51567. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51568. }
  51569. else {
  51570. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51571. }
  51572. }
  51573. }
  51574. else {
  51575. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51576. }
  51577. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51578. this._blendingFactor += blendingSpeed;
  51579. }
  51580. else {
  51581. this._currentValue = currentValue;
  51582. }
  51583. if (weight !== -1.0) {
  51584. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51585. }
  51586. else {
  51587. destination[path] = this._currentValue;
  51588. }
  51589. if (target.markAsDirty) {
  51590. target.markAsDirty(this._animation.targetProperty);
  51591. }
  51592. };
  51593. /**
  51594. * Gets the loop pmode of the runtime animation
  51595. * @returns Loop Mode
  51596. */
  51597. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51598. if (this._target && this._target.animationPropertiesOverride) {
  51599. return this._target.animationPropertiesOverride.loopMode;
  51600. }
  51601. return this._animation.loopMode;
  51602. };
  51603. /**
  51604. * Move the current animation to a given frame
  51605. * @param frame defines the frame to move to
  51606. */
  51607. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51608. var keys = this._animation.getKeys();
  51609. if (frame < keys[0].frame) {
  51610. frame = keys[0].frame;
  51611. }
  51612. else if (frame > keys[keys.length - 1].frame) {
  51613. frame = keys[keys.length - 1].frame;
  51614. }
  51615. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51616. this.setValue(currentValue, -1);
  51617. };
  51618. /**
  51619. * @hidden Internal use only
  51620. */
  51621. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51622. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51623. this._ratioOffset = this._previousRatio - newRatio;
  51624. };
  51625. /**
  51626. * Execute the current animation
  51627. * @param delay defines the delay to add to the current frame
  51628. * @param from defines the lower bound of the animation range
  51629. * @param to defines the upper bound of the animation range
  51630. * @param loop defines if the current animation must loop
  51631. * @param speedRatio defines the current speed ratio
  51632. * @param weight defines the weight of the animation (default is -1 so no weight)
  51633. * @returns a boolean indicating if the animation is running
  51634. */
  51635. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51636. if (weight === void 0) { weight = -1.0; }
  51637. var targetPropertyPath = this._animation.targetPropertyPath;
  51638. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51639. this._stopped = true;
  51640. return false;
  51641. }
  51642. var returnValue = true;
  51643. var keys = this._animation.getKeys();
  51644. // Adding a start key at frame 0 if missing
  51645. if (keys[0].frame !== 0) {
  51646. var newKey = { frame: 0, value: keys[0].value };
  51647. keys.splice(0, 0, newKey);
  51648. }
  51649. // Adding a duplicate key when there is only one key at frame zero
  51650. else if (keys.length === 1) {
  51651. var newKey = { frame: 0.001, value: keys[0].value };
  51652. keys.push(newKey);
  51653. }
  51654. // Check limits
  51655. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51656. from = keys[0].frame;
  51657. }
  51658. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51659. to = keys[keys.length - 1].frame;
  51660. }
  51661. //to and from cannot be the same key
  51662. if (from === to) {
  51663. if (from > keys[0].frame) {
  51664. from--;
  51665. }
  51666. else if (to < keys[keys.length - 1].frame) {
  51667. to++;
  51668. }
  51669. }
  51670. // Compute ratio
  51671. var range = to - from;
  51672. var offsetValue;
  51673. // ratio represents the frame delta between from and to
  51674. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51675. var highLimitValue = 0;
  51676. this._previousDelay = delay;
  51677. this._previousRatio = ratio;
  51678. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51679. returnValue = false;
  51680. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51681. }
  51682. else {
  51683. // Get max value if required
  51684. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51685. var keyOffset = to.toString() + from.toString();
  51686. if (!this._offsetsCache[keyOffset]) {
  51687. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51688. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51689. switch (this._animation.dataType) {
  51690. // Float
  51691. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51692. this._offsetsCache[keyOffset] = toValue - fromValue;
  51693. break;
  51694. // Quaternion
  51695. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51696. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51697. break;
  51698. // Vector3
  51699. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51700. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51701. // Vector2
  51702. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51703. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51704. // Size
  51705. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51706. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51707. // Color3
  51708. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51709. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51710. default:
  51711. break;
  51712. }
  51713. this._highLimitsCache[keyOffset] = toValue;
  51714. }
  51715. highLimitValue = this._highLimitsCache[keyOffset];
  51716. offsetValue = this._offsetsCache[keyOffset];
  51717. }
  51718. }
  51719. if (offsetValue === undefined) {
  51720. switch (this._animation.dataType) {
  51721. // Float
  51722. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51723. offsetValue = 0;
  51724. break;
  51725. // Quaternion
  51726. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51727. offsetValue = _staticOffsetValueQuaternion;
  51728. break;
  51729. // Vector3
  51730. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51731. offsetValue = _staticOffsetValueVector3;
  51732. break;
  51733. // Vector2
  51734. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51735. offsetValue = _staticOffsetValueVector2;
  51736. break;
  51737. // Size
  51738. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51739. offsetValue = _staticOffsetValueSize;
  51740. break;
  51741. // Color3
  51742. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51743. offsetValue = _staticOffsetValueColor3;
  51744. }
  51745. }
  51746. // Compute value
  51747. var repeatCount = (ratio / range) >> 0;
  51748. var currentFrame = returnValue ? from + ratio % range : to;
  51749. // Need to normalize?
  51750. if (this._host && this._host.syncRoot) {
  51751. var syncRoot = this._host.syncRoot;
  51752. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51753. currentFrame = from + (to - from) * hostNormalizedFrame;
  51754. }
  51755. // Reset events if looping
  51756. var events = this._events;
  51757. if (range > 0 && this.currentFrame > currentFrame ||
  51758. range < 0 && this.currentFrame < currentFrame) {
  51759. // Need to reset animation events
  51760. for (var index = 0; index < events.length; index++) {
  51761. if (!events[index].onlyOnce) {
  51762. // reset event, the animation is looping
  51763. events[index].isDone = false;
  51764. }
  51765. }
  51766. }
  51767. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51768. // Set value
  51769. this.setValue(currentValue, weight);
  51770. // Check events
  51771. for (var index = 0; index < events.length; index++) {
  51772. // Make sure current frame has passed event frame and that event frame is within the current range
  51773. // Also, handle both forward and reverse animations
  51774. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51775. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51776. var event = events[index];
  51777. if (!event.isDone) {
  51778. // If event should be done only once, remove it.
  51779. if (event.onlyOnce) {
  51780. events.splice(index, 1);
  51781. index--;
  51782. }
  51783. event.isDone = true;
  51784. event.action(currentFrame);
  51785. } // Don't do anything if the event has already be done.
  51786. }
  51787. }
  51788. if (!returnValue) {
  51789. this._stopped = true;
  51790. }
  51791. return returnValue;
  51792. };
  51793. return RuntimeAnimation;
  51794. }());
  51795. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51796. })(BABYLON || (BABYLON = {}));
  51797. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51798. var BABYLON;
  51799. (function (BABYLON) {
  51800. /**
  51801. * Class used to store an actual running animation
  51802. */
  51803. var Animatable = /** @class */ (function () {
  51804. /**
  51805. * Creates a new Animatable
  51806. * @param scene defines the hosting scene
  51807. * @param target defines the target object
  51808. * @param fromFrame defines the starting frame number (default is 0)
  51809. * @param toFrame defines the ending frame number (default is 100)
  51810. * @param loopAnimation defines if the animation must loop (default is false)
  51811. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51812. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51813. * @param animations defines a group of animation to add to the new Animatable
  51814. */
  51815. function Animatable(scene,
  51816. /** defines the target object */
  51817. target,
  51818. /** defines the starting frame number (default is 0) */
  51819. fromFrame,
  51820. /** defines the ending frame number (default is 100) */
  51821. toFrame,
  51822. /** defines if the animation must loop (default is false) */
  51823. loopAnimation, speedRatio,
  51824. /** defines a callback to call when animation ends if it is not looping */
  51825. onAnimationEnd, animations) {
  51826. if (fromFrame === void 0) { fromFrame = 0; }
  51827. if (toFrame === void 0) { toFrame = 100; }
  51828. if (loopAnimation === void 0) { loopAnimation = false; }
  51829. if (speedRatio === void 0) { speedRatio = 1.0; }
  51830. this.target = target;
  51831. this.fromFrame = fromFrame;
  51832. this.toFrame = toFrame;
  51833. this.loopAnimation = loopAnimation;
  51834. this.onAnimationEnd = onAnimationEnd;
  51835. this._localDelayOffset = null;
  51836. this._pausedDelay = null;
  51837. this._runtimeAnimations = new Array();
  51838. this._paused = false;
  51839. this._speedRatio = 1;
  51840. this._weight = -1.0;
  51841. /**
  51842. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51843. * This will only apply for non looping animation (default is true)
  51844. */
  51845. this.disposeOnEnd = true;
  51846. /**
  51847. * Gets a boolean indicating if the animation has started
  51848. */
  51849. this.animationStarted = false;
  51850. /**
  51851. * Observer raised when the animation ends
  51852. */
  51853. this.onAnimationEndObservable = new BABYLON.Observable();
  51854. this._scene = scene;
  51855. if (animations) {
  51856. this.appendAnimations(target, animations);
  51857. }
  51858. this._speedRatio = speedRatio;
  51859. scene._activeAnimatables.push(this);
  51860. }
  51861. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51862. /**
  51863. * Gets the root Animatable used to synchronize and normalize animations
  51864. */
  51865. get: function () {
  51866. return this._syncRoot;
  51867. },
  51868. enumerable: true,
  51869. configurable: true
  51870. });
  51871. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51872. /**
  51873. * Gets the current frame of the first RuntimeAnimation
  51874. * Used to synchronize Animatables
  51875. */
  51876. get: function () {
  51877. if (this._runtimeAnimations.length === 0) {
  51878. return 0;
  51879. }
  51880. return this._runtimeAnimations[0].currentFrame;
  51881. },
  51882. enumerable: true,
  51883. configurable: true
  51884. });
  51885. Object.defineProperty(Animatable.prototype, "weight", {
  51886. /**
  51887. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51888. */
  51889. get: function () {
  51890. return this._weight;
  51891. },
  51892. set: function (value) {
  51893. if (value === -1) { // -1 is ok and means no weight
  51894. this._weight = -1;
  51895. return;
  51896. }
  51897. // Else weight must be in [0, 1] range
  51898. this._weight = Math.min(Math.max(value, 0), 1.0);
  51899. },
  51900. enumerable: true,
  51901. configurable: true
  51902. });
  51903. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51904. /**
  51905. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51906. */
  51907. get: function () {
  51908. return this._speedRatio;
  51909. },
  51910. set: function (value) {
  51911. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51912. var animation = this._runtimeAnimations[index];
  51913. animation._prepareForSpeedRatioChange(value);
  51914. }
  51915. this._speedRatio = value;
  51916. },
  51917. enumerable: true,
  51918. configurable: true
  51919. });
  51920. // Methods
  51921. /**
  51922. * Synchronize and normalize current Animatable with a source Animatable
  51923. * This is useful when using animation weights and when animations are not of the same length
  51924. * @param root defines the root Animatable to synchronize with
  51925. * @returns the current Animatable
  51926. */
  51927. Animatable.prototype.syncWith = function (root) {
  51928. this._syncRoot = root;
  51929. if (root) {
  51930. // Make sure this animatable will animate after the root
  51931. var index = this._scene._activeAnimatables.indexOf(this);
  51932. if (index > -1) {
  51933. this._scene._activeAnimatables.splice(index, 1);
  51934. this._scene._activeAnimatables.push(this);
  51935. }
  51936. }
  51937. return this;
  51938. };
  51939. /**
  51940. * Gets the list of runtime animations
  51941. * @returns an array of RuntimeAnimation
  51942. */
  51943. Animatable.prototype.getAnimations = function () {
  51944. return this._runtimeAnimations;
  51945. };
  51946. /**
  51947. * Adds more animations to the current animatable
  51948. * @param target defines the target of the animations
  51949. * @param animations defines the new animations to add
  51950. */
  51951. Animatable.prototype.appendAnimations = function (target, animations) {
  51952. for (var index = 0; index < animations.length; index++) {
  51953. var animation = animations[index];
  51954. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51955. }
  51956. };
  51957. /**
  51958. * Gets the source animation for a specific property
  51959. * @param property defines the propertyu to look for
  51960. * @returns null or the source animation for the given property
  51961. */
  51962. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51963. var runtimeAnimations = this._runtimeAnimations;
  51964. for (var index = 0; index < runtimeAnimations.length; index++) {
  51965. if (runtimeAnimations[index].animation.targetProperty === property) {
  51966. return runtimeAnimations[index].animation;
  51967. }
  51968. }
  51969. return null;
  51970. };
  51971. /**
  51972. * Gets the runtime animation for a specific property
  51973. * @param property defines the propertyu to look for
  51974. * @returns null or the runtime animation for the given property
  51975. */
  51976. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51977. var runtimeAnimations = this._runtimeAnimations;
  51978. for (var index = 0; index < runtimeAnimations.length; index++) {
  51979. if (runtimeAnimations[index].animation.targetProperty === property) {
  51980. return runtimeAnimations[index];
  51981. }
  51982. }
  51983. return null;
  51984. };
  51985. /**
  51986. * Resets the animatable to its original state
  51987. */
  51988. Animatable.prototype.reset = function () {
  51989. var runtimeAnimations = this._runtimeAnimations;
  51990. for (var index = 0; index < runtimeAnimations.length; index++) {
  51991. runtimeAnimations[index].reset(true);
  51992. }
  51993. this._localDelayOffset = null;
  51994. this._pausedDelay = null;
  51995. };
  51996. /**
  51997. * Allows the animatable to blend with current running animations
  51998. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51999. * @param blendingSpeed defines the blending speed to use
  52000. */
  52001. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52002. var runtimeAnimations = this._runtimeAnimations;
  52003. for (var index = 0; index < runtimeAnimations.length; index++) {
  52004. runtimeAnimations[index].animation.enableBlending = true;
  52005. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52006. }
  52007. };
  52008. /**
  52009. * Disable animation blending
  52010. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  52011. */
  52012. Animatable.prototype.disableBlending = function () {
  52013. var runtimeAnimations = this._runtimeAnimations;
  52014. for (var index = 0; index < runtimeAnimations.length; index++) {
  52015. runtimeAnimations[index].animation.enableBlending = false;
  52016. }
  52017. };
  52018. /**
  52019. * Jump directly to a given frame
  52020. * @param frame defines the frame to jump to
  52021. */
  52022. Animatable.prototype.goToFrame = function (frame) {
  52023. var runtimeAnimations = this._runtimeAnimations;
  52024. if (runtimeAnimations[0]) {
  52025. var fps = runtimeAnimations[0].animation.framePerSecond;
  52026. var currentFrame = runtimeAnimations[0].currentFrame;
  52027. var adjustTime = frame - currentFrame;
  52028. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52029. if (this._localDelayOffset === null) {
  52030. this._localDelayOffset = 0;
  52031. }
  52032. this._localDelayOffset -= delay;
  52033. }
  52034. for (var index = 0; index < runtimeAnimations.length; index++) {
  52035. runtimeAnimations[index].goToFrame(frame);
  52036. }
  52037. };
  52038. /**
  52039. * Pause the animation
  52040. */
  52041. Animatable.prototype.pause = function () {
  52042. if (this._paused) {
  52043. return;
  52044. }
  52045. this._paused = true;
  52046. };
  52047. /**
  52048. * Restart the animation
  52049. */
  52050. Animatable.prototype.restart = function () {
  52051. this._paused = false;
  52052. };
  52053. Animatable.prototype._raiseOnAnimationEnd = function () {
  52054. if (this.onAnimationEnd) {
  52055. this.onAnimationEnd();
  52056. }
  52057. this.onAnimationEndObservable.notifyObservers(this);
  52058. };
  52059. /**
  52060. * Stop and delete the current animation
  52061. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  52062. * @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)
  52063. */
  52064. Animatable.prototype.stop = function (animationName, targetMask) {
  52065. if (animationName || targetMask) {
  52066. var idx = this._scene._activeAnimatables.indexOf(this);
  52067. if (idx > -1) {
  52068. var runtimeAnimations = this._runtimeAnimations;
  52069. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52070. var runtimeAnimation = runtimeAnimations[index];
  52071. if (animationName && runtimeAnimation.animation.name != animationName) {
  52072. continue;
  52073. }
  52074. if (targetMask && !targetMask(runtimeAnimation.target)) {
  52075. continue;
  52076. }
  52077. runtimeAnimation.dispose();
  52078. runtimeAnimations.splice(index, 1);
  52079. }
  52080. if (runtimeAnimations.length == 0) {
  52081. this._scene._activeAnimatables.splice(idx, 1);
  52082. this._raiseOnAnimationEnd();
  52083. }
  52084. }
  52085. }
  52086. else {
  52087. var index = this._scene._activeAnimatables.indexOf(this);
  52088. if (index > -1) {
  52089. this._scene._activeAnimatables.splice(index, 1);
  52090. var runtimeAnimations = this._runtimeAnimations;
  52091. for (var index = 0; index < runtimeAnimations.length; index++) {
  52092. runtimeAnimations[index].dispose();
  52093. }
  52094. this._raiseOnAnimationEnd();
  52095. }
  52096. }
  52097. };
  52098. /**
  52099. * Wait asynchronously for the animation to end
  52100. * @returns a promise which will be fullfilled when the animation ends
  52101. */
  52102. Animatable.prototype.waitAsync = function () {
  52103. var _this = this;
  52104. return new Promise(function (resolve, reject) {
  52105. _this.onAnimationEndObservable.add(function () {
  52106. resolve(_this);
  52107. }, undefined, undefined, _this, true);
  52108. });
  52109. };
  52110. /** @hidden */
  52111. Animatable.prototype._animate = function (delay) {
  52112. if (this._paused) {
  52113. this.animationStarted = false;
  52114. if (this._pausedDelay === null) {
  52115. this._pausedDelay = delay;
  52116. }
  52117. return true;
  52118. }
  52119. if (this._localDelayOffset === null) {
  52120. this._localDelayOffset = delay;
  52121. this._pausedDelay = null;
  52122. }
  52123. else if (this._pausedDelay !== null) {
  52124. this._localDelayOffset += delay - this._pausedDelay;
  52125. this._pausedDelay = null;
  52126. }
  52127. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52128. return true;
  52129. }
  52130. // Animating
  52131. var running = false;
  52132. var runtimeAnimations = this._runtimeAnimations;
  52133. var index;
  52134. for (index = 0; index < runtimeAnimations.length; index++) {
  52135. var animation = runtimeAnimations[index];
  52136. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52137. running = running || isRunning;
  52138. }
  52139. this.animationStarted = running;
  52140. if (!running) {
  52141. if (this.disposeOnEnd) {
  52142. // Remove from active animatables
  52143. index = this._scene._activeAnimatables.indexOf(this);
  52144. this._scene._activeAnimatables.splice(index, 1);
  52145. // Dispose all runtime animations
  52146. for (index = 0; index < runtimeAnimations.length; index++) {
  52147. runtimeAnimations[index].dispose();
  52148. }
  52149. }
  52150. this._raiseOnAnimationEnd();
  52151. if (this.disposeOnEnd) {
  52152. this.onAnimationEnd = null;
  52153. this.onAnimationEndObservable.clear();
  52154. }
  52155. }
  52156. return running;
  52157. };
  52158. return Animatable;
  52159. }());
  52160. BABYLON.Animatable = Animatable;
  52161. })(BABYLON || (BABYLON = {}));
  52162. //# sourceMappingURL=babylon.animatable.js.map
  52163. var BABYLON;
  52164. (function (BABYLON) {
  52165. var EasingFunction = /** @class */ (function () {
  52166. function EasingFunction() {
  52167. // Properties
  52168. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52169. }
  52170. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52171. get: function () {
  52172. return EasingFunction._EASINGMODE_EASEIN;
  52173. },
  52174. enumerable: true,
  52175. configurable: true
  52176. });
  52177. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52178. get: function () {
  52179. return EasingFunction._EASINGMODE_EASEOUT;
  52180. },
  52181. enumerable: true,
  52182. configurable: true
  52183. });
  52184. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52185. get: function () {
  52186. return EasingFunction._EASINGMODE_EASEINOUT;
  52187. },
  52188. enumerable: true,
  52189. configurable: true
  52190. });
  52191. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52192. var n = Math.min(Math.max(easingMode, 0), 2);
  52193. this._easingMode = n;
  52194. };
  52195. EasingFunction.prototype.getEasingMode = function () {
  52196. return this._easingMode;
  52197. };
  52198. EasingFunction.prototype.easeInCore = function (gradient) {
  52199. throw new Error('You must implement this method');
  52200. };
  52201. EasingFunction.prototype.ease = function (gradient) {
  52202. switch (this._easingMode) {
  52203. case EasingFunction.EASINGMODE_EASEIN:
  52204. return this.easeInCore(gradient);
  52205. case EasingFunction.EASINGMODE_EASEOUT:
  52206. return (1 - this.easeInCore(1 - gradient));
  52207. }
  52208. if (gradient >= 0.5) {
  52209. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52210. }
  52211. return (this.easeInCore(gradient * 2) * 0.5);
  52212. };
  52213. //Statics
  52214. EasingFunction._EASINGMODE_EASEIN = 0;
  52215. EasingFunction._EASINGMODE_EASEOUT = 1;
  52216. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52217. return EasingFunction;
  52218. }());
  52219. BABYLON.EasingFunction = EasingFunction;
  52220. var CircleEase = /** @class */ (function (_super) {
  52221. __extends(CircleEase, _super);
  52222. function CircleEase() {
  52223. return _super !== null && _super.apply(this, arguments) || this;
  52224. }
  52225. CircleEase.prototype.easeInCore = function (gradient) {
  52226. gradient = Math.max(0, Math.min(1, gradient));
  52227. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52228. };
  52229. return CircleEase;
  52230. }(EasingFunction));
  52231. BABYLON.CircleEase = CircleEase;
  52232. var BackEase = /** @class */ (function (_super) {
  52233. __extends(BackEase, _super);
  52234. function BackEase(amplitude) {
  52235. if (amplitude === void 0) { amplitude = 1; }
  52236. var _this = _super.call(this) || this;
  52237. _this.amplitude = amplitude;
  52238. return _this;
  52239. }
  52240. BackEase.prototype.easeInCore = function (gradient) {
  52241. var num = Math.max(0, this.amplitude);
  52242. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52243. };
  52244. return BackEase;
  52245. }(EasingFunction));
  52246. BABYLON.BackEase = BackEase;
  52247. var BounceEase = /** @class */ (function (_super) {
  52248. __extends(BounceEase, _super);
  52249. function BounceEase(bounces, bounciness) {
  52250. if (bounces === void 0) { bounces = 3; }
  52251. if (bounciness === void 0) { bounciness = 2; }
  52252. var _this = _super.call(this) || this;
  52253. _this.bounces = bounces;
  52254. _this.bounciness = bounciness;
  52255. return _this;
  52256. }
  52257. BounceEase.prototype.easeInCore = function (gradient) {
  52258. var y = Math.max(0.0, this.bounces);
  52259. var bounciness = this.bounciness;
  52260. if (bounciness <= 1.0) {
  52261. bounciness = 1.001;
  52262. }
  52263. var num9 = Math.pow(bounciness, y);
  52264. var num5 = 1.0 - bounciness;
  52265. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52266. var num15 = gradient * num4;
  52267. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52268. var num3 = Math.floor(num65);
  52269. var num13 = num3 + 1.0;
  52270. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52271. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52272. var num7 = (num8 + num12) * 0.5;
  52273. var num6 = gradient - num7;
  52274. var num2 = num7 - num8;
  52275. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52276. };
  52277. return BounceEase;
  52278. }(EasingFunction));
  52279. BABYLON.BounceEase = BounceEase;
  52280. var CubicEase = /** @class */ (function (_super) {
  52281. __extends(CubicEase, _super);
  52282. function CubicEase() {
  52283. return _super !== null && _super.apply(this, arguments) || this;
  52284. }
  52285. CubicEase.prototype.easeInCore = function (gradient) {
  52286. return (gradient * gradient * gradient);
  52287. };
  52288. return CubicEase;
  52289. }(EasingFunction));
  52290. BABYLON.CubicEase = CubicEase;
  52291. var ElasticEase = /** @class */ (function (_super) {
  52292. __extends(ElasticEase, _super);
  52293. function ElasticEase(oscillations, springiness) {
  52294. if (oscillations === void 0) { oscillations = 3; }
  52295. if (springiness === void 0) { springiness = 3; }
  52296. var _this = _super.call(this) || this;
  52297. _this.oscillations = oscillations;
  52298. _this.springiness = springiness;
  52299. return _this;
  52300. }
  52301. ElasticEase.prototype.easeInCore = function (gradient) {
  52302. var num2;
  52303. var num3 = Math.max(0.0, this.oscillations);
  52304. var num = Math.max(0.0, this.springiness);
  52305. if (num == 0) {
  52306. num2 = gradient;
  52307. }
  52308. else {
  52309. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52310. }
  52311. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52312. };
  52313. return ElasticEase;
  52314. }(EasingFunction));
  52315. BABYLON.ElasticEase = ElasticEase;
  52316. var ExponentialEase = /** @class */ (function (_super) {
  52317. __extends(ExponentialEase, _super);
  52318. function ExponentialEase(exponent) {
  52319. if (exponent === void 0) { exponent = 2; }
  52320. var _this = _super.call(this) || this;
  52321. _this.exponent = exponent;
  52322. return _this;
  52323. }
  52324. ExponentialEase.prototype.easeInCore = function (gradient) {
  52325. if (this.exponent <= 0) {
  52326. return gradient;
  52327. }
  52328. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52329. };
  52330. return ExponentialEase;
  52331. }(EasingFunction));
  52332. BABYLON.ExponentialEase = ExponentialEase;
  52333. var PowerEase = /** @class */ (function (_super) {
  52334. __extends(PowerEase, _super);
  52335. function PowerEase(power) {
  52336. if (power === void 0) { power = 2; }
  52337. var _this = _super.call(this) || this;
  52338. _this.power = power;
  52339. return _this;
  52340. }
  52341. PowerEase.prototype.easeInCore = function (gradient) {
  52342. var y = Math.max(0.0, this.power);
  52343. return Math.pow(gradient, y);
  52344. };
  52345. return PowerEase;
  52346. }(EasingFunction));
  52347. BABYLON.PowerEase = PowerEase;
  52348. var QuadraticEase = /** @class */ (function (_super) {
  52349. __extends(QuadraticEase, _super);
  52350. function QuadraticEase() {
  52351. return _super !== null && _super.apply(this, arguments) || this;
  52352. }
  52353. QuadraticEase.prototype.easeInCore = function (gradient) {
  52354. return (gradient * gradient);
  52355. };
  52356. return QuadraticEase;
  52357. }(EasingFunction));
  52358. BABYLON.QuadraticEase = QuadraticEase;
  52359. var QuarticEase = /** @class */ (function (_super) {
  52360. __extends(QuarticEase, _super);
  52361. function QuarticEase() {
  52362. return _super !== null && _super.apply(this, arguments) || this;
  52363. }
  52364. QuarticEase.prototype.easeInCore = function (gradient) {
  52365. return (gradient * gradient * gradient * gradient);
  52366. };
  52367. return QuarticEase;
  52368. }(EasingFunction));
  52369. BABYLON.QuarticEase = QuarticEase;
  52370. var QuinticEase = /** @class */ (function (_super) {
  52371. __extends(QuinticEase, _super);
  52372. function QuinticEase() {
  52373. return _super !== null && _super.apply(this, arguments) || this;
  52374. }
  52375. QuinticEase.prototype.easeInCore = function (gradient) {
  52376. return (gradient * gradient * gradient * gradient * gradient);
  52377. };
  52378. return QuinticEase;
  52379. }(EasingFunction));
  52380. BABYLON.QuinticEase = QuinticEase;
  52381. var SineEase = /** @class */ (function (_super) {
  52382. __extends(SineEase, _super);
  52383. function SineEase() {
  52384. return _super !== null && _super.apply(this, arguments) || this;
  52385. }
  52386. SineEase.prototype.easeInCore = function (gradient) {
  52387. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52388. };
  52389. return SineEase;
  52390. }(EasingFunction));
  52391. BABYLON.SineEase = SineEase;
  52392. var BezierCurveEase = /** @class */ (function (_super) {
  52393. __extends(BezierCurveEase, _super);
  52394. function BezierCurveEase(x1, y1, x2, y2) {
  52395. if (x1 === void 0) { x1 = 0; }
  52396. if (y1 === void 0) { y1 = 0; }
  52397. if (x2 === void 0) { x2 = 1; }
  52398. if (y2 === void 0) { y2 = 1; }
  52399. var _this = _super.call(this) || this;
  52400. _this.x1 = x1;
  52401. _this.y1 = y1;
  52402. _this.x2 = x2;
  52403. _this.y2 = y2;
  52404. return _this;
  52405. }
  52406. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52407. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52408. };
  52409. return BezierCurveEase;
  52410. }(EasingFunction));
  52411. BABYLON.BezierCurveEase = BezierCurveEase;
  52412. })(BABYLON || (BABYLON = {}));
  52413. //# sourceMappingURL=babylon.easing.js.map
  52414. var BABYLON;
  52415. (function (BABYLON) {
  52416. /**
  52417. * A Condition applied to an Action
  52418. */
  52419. var Condition = /** @class */ (function () {
  52420. /**
  52421. * Creates a new Condition
  52422. * @param actionManager the manager of the action the condition is applied to
  52423. */
  52424. function Condition(actionManager) {
  52425. this._actionManager = actionManager;
  52426. }
  52427. /**
  52428. * Check if the current condition is valid
  52429. * @returns a boolean
  52430. */
  52431. Condition.prototype.isValid = function () {
  52432. return true;
  52433. };
  52434. /**
  52435. * Internal only
  52436. * @hidden
  52437. */
  52438. Condition.prototype._getProperty = function (propertyPath) {
  52439. return this._actionManager._getProperty(propertyPath);
  52440. };
  52441. /**
  52442. * Internal only
  52443. * @hidden
  52444. */
  52445. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52446. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52447. };
  52448. /**
  52449. * Serialize placeholder for child classes
  52450. * @returns the serialized object
  52451. */
  52452. Condition.prototype.serialize = function () {
  52453. };
  52454. /**
  52455. * Internal only
  52456. * @hidden
  52457. */
  52458. Condition.prototype._serialize = function (serializedCondition) {
  52459. return {
  52460. type: 2,
  52461. children: [],
  52462. name: serializedCondition.name,
  52463. properties: serializedCondition.properties
  52464. };
  52465. };
  52466. return Condition;
  52467. }());
  52468. BABYLON.Condition = Condition;
  52469. /**
  52470. * Defines specific conditional operators as extensions of Condition
  52471. */
  52472. var ValueCondition = /** @class */ (function (_super) {
  52473. __extends(ValueCondition, _super);
  52474. /**
  52475. * Creates a new ValueCondition
  52476. * @param actionManager manager for the action the condition applies to
  52477. * @param target for the action
  52478. * @param propertyPath path to specify the property of the target the conditional operator uses
  52479. * @param value the value compared by the conditional operator against the current value of the property
  52480. * @param operator the conditional operator, default ValueCondition.IsEqual
  52481. */
  52482. function ValueCondition(actionManager, target,
  52483. /** path to specify the property of the target the conditional operator uses */
  52484. propertyPath,
  52485. /** the value compared by the conditional operator against the current value of the property */
  52486. value,
  52487. /** the conditional operator, default ValueCondition.IsEqual */
  52488. operator) {
  52489. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52490. var _this = _super.call(this, actionManager) || this;
  52491. _this.propertyPath = propertyPath;
  52492. _this.value = value;
  52493. _this.operator = operator;
  52494. _this._target = target;
  52495. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52496. _this._property = _this._getProperty(_this.propertyPath);
  52497. return _this;
  52498. }
  52499. Object.defineProperty(ValueCondition, "IsEqual", {
  52500. /**
  52501. * returns the number for IsEqual
  52502. */
  52503. get: function () {
  52504. return ValueCondition._IsEqual;
  52505. },
  52506. enumerable: true,
  52507. configurable: true
  52508. });
  52509. Object.defineProperty(ValueCondition, "IsDifferent", {
  52510. /**
  52511. * Returns the number for IsDifferent
  52512. */
  52513. get: function () {
  52514. return ValueCondition._IsDifferent;
  52515. },
  52516. enumerable: true,
  52517. configurable: true
  52518. });
  52519. Object.defineProperty(ValueCondition, "IsGreater", {
  52520. /**
  52521. * Returns the number for IsGreater
  52522. */
  52523. get: function () {
  52524. return ValueCondition._IsGreater;
  52525. },
  52526. enumerable: true,
  52527. configurable: true
  52528. });
  52529. Object.defineProperty(ValueCondition, "IsLesser", {
  52530. /**
  52531. * Returns the number for IsLesser
  52532. */
  52533. get: function () {
  52534. return ValueCondition._IsLesser;
  52535. },
  52536. enumerable: true,
  52537. configurable: true
  52538. });
  52539. /**
  52540. * Compares the given value with the property value for the specified conditional operator
  52541. * @returns the result of the comparison
  52542. */
  52543. ValueCondition.prototype.isValid = function () {
  52544. switch (this.operator) {
  52545. case ValueCondition.IsGreater:
  52546. return this._effectiveTarget[this._property] > this.value;
  52547. case ValueCondition.IsLesser:
  52548. return this._effectiveTarget[this._property] < this.value;
  52549. case ValueCondition.IsEqual:
  52550. case ValueCondition.IsDifferent:
  52551. var check;
  52552. if (this.value.equals) {
  52553. check = this.value.equals(this._effectiveTarget[this._property]);
  52554. }
  52555. else {
  52556. check = this.value === this._effectiveTarget[this._property];
  52557. }
  52558. return this.operator === ValueCondition.IsEqual ? check : !check;
  52559. }
  52560. return false;
  52561. };
  52562. /**
  52563. * Serialize the ValueCondition into a JSON compatible object
  52564. * @returns serialization object
  52565. */
  52566. ValueCondition.prototype.serialize = function () {
  52567. return this._serialize({
  52568. name: "ValueCondition",
  52569. properties: [
  52570. BABYLON.Action._GetTargetProperty(this._target),
  52571. { name: "propertyPath", value: this.propertyPath },
  52572. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52573. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52574. ]
  52575. });
  52576. };
  52577. /**
  52578. * Gets the name of the conditional operator for the ValueCondition
  52579. * @param operator the conditional operator
  52580. * @returns the name
  52581. */
  52582. ValueCondition.GetOperatorName = function (operator) {
  52583. switch (operator) {
  52584. case ValueCondition._IsEqual: return "IsEqual";
  52585. case ValueCondition._IsDifferent: return "IsDifferent";
  52586. case ValueCondition._IsGreater: return "IsGreater";
  52587. case ValueCondition._IsLesser: return "IsLesser";
  52588. default: return "";
  52589. }
  52590. };
  52591. /**
  52592. * Internal only
  52593. * @hidden
  52594. */
  52595. ValueCondition._IsEqual = 0;
  52596. /**
  52597. * Internal only
  52598. * @hidden
  52599. */
  52600. ValueCondition._IsDifferent = 1;
  52601. /**
  52602. * Internal only
  52603. * @hidden
  52604. */
  52605. ValueCondition._IsGreater = 2;
  52606. /**
  52607. * Internal only
  52608. * @hidden
  52609. */
  52610. ValueCondition._IsLesser = 3;
  52611. return ValueCondition;
  52612. }(Condition));
  52613. BABYLON.ValueCondition = ValueCondition;
  52614. /**
  52615. * Defines a predicate condition as an extension of Condition
  52616. */
  52617. var PredicateCondition = /** @class */ (function (_super) {
  52618. __extends(PredicateCondition, _super);
  52619. /**
  52620. * Creates a new PredicateCondition
  52621. * @param actionManager manager for the action the condition applies to
  52622. * @param predicate defines the predicate function used to validate the condition
  52623. */
  52624. function PredicateCondition(actionManager,
  52625. /** defines the predicate function used to validate the condition */
  52626. predicate) {
  52627. var _this = _super.call(this, actionManager) || this;
  52628. _this.predicate = predicate;
  52629. return _this;
  52630. }
  52631. /**
  52632. * @returns the validity of the predicate condition
  52633. */
  52634. PredicateCondition.prototype.isValid = function () {
  52635. return this.predicate();
  52636. };
  52637. return PredicateCondition;
  52638. }(Condition));
  52639. BABYLON.PredicateCondition = PredicateCondition;
  52640. /**
  52641. * Defines a state condition as an extension of Condition
  52642. */
  52643. var StateCondition = /** @class */ (function (_super) {
  52644. __extends(StateCondition, _super);
  52645. /**
  52646. * Creates a new StateCondition
  52647. * @param actionManager manager for the action the condition applies to
  52648. * @param target of the condition
  52649. * @param value to compare with target state
  52650. */
  52651. function StateCondition(actionManager, target, value) {
  52652. var _this = _super.call(this, actionManager) || this;
  52653. _this.value = value;
  52654. _this._target = target;
  52655. return _this;
  52656. }
  52657. /**
  52658. * @returns the validity of the state
  52659. */
  52660. StateCondition.prototype.isValid = function () {
  52661. return this._target.state === this.value;
  52662. };
  52663. /**
  52664. * Serialize the StateCondition into a JSON compatible object
  52665. * @returns serialization object
  52666. */
  52667. StateCondition.prototype.serialize = function () {
  52668. return this._serialize({
  52669. name: "StateCondition",
  52670. properties: [
  52671. BABYLON.Action._GetTargetProperty(this._target),
  52672. { name: "value", value: this.value }
  52673. ]
  52674. });
  52675. };
  52676. return StateCondition;
  52677. }(Condition));
  52678. BABYLON.StateCondition = StateCondition;
  52679. })(BABYLON || (BABYLON = {}));
  52680. //# sourceMappingURL=babylon.condition.js.map
  52681. var BABYLON;
  52682. (function (BABYLON) {
  52683. /**
  52684. * The action to be carried out following a trigger
  52685. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52686. */
  52687. var Action = /** @class */ (function () {
  52688. /**
  52689. * Creates a new Action
  52690. * @param triggerOptions the trigger, with or without parameters, for the action
  52691. * @param condition an optional determinant of action
  52692. */
  52693. function Action(
  52694. /** the trigger, with or without parameters, for the action */
  52695. triggerOptions, condition) {
  52696. this.triggerOptions = triggerOptions;
  52697. /**
  52698. * An event triggered prior to action being executed.
  52699. */
  52700. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52701. if (triggerOptions.parameter) {
  52702. this.trigger = triggerOptions.trigger;
  52703. this._triggerParameter = triggerOptions.parameter;
  52704. }
  52705. else if (triggerOptions.trigger) {
  52706. this.trigger = triggerOptions.trigger;
  52707. }
  52708. else {
  52709. this.trigger = triggerOptions;
  52710. }
  52711. this._nextActiveAction = this;
  52712. this._condition = condition;
  52713. }
  52714. /**
  52715. * Internal only
  52716. * @hidden
  52717. */
  52718. Action.prototype._prepare = function () {
  52719. };
  52720. /**
  52721. * Gets the trigger parameters
  52722. * @returns the trigger parameters
  52723. */
  52724. Action.prototype.getTriggerParameter = function () {
  52725. return this._triggerParameter;
  52726. };
  52727. /**
  52728. * Internal only - executes current action event
  52729. * @hidden
  52730. */
  52731. Action.prototype._executeCurrent = function (evt) {
  52732. if (this._nextActiveAction._condition) {
  52733. var condition = this._nextActiveAction._condition;
  52734. var currentRenderId = this._actionManager.getScene().getRenderId();
  52735. // We cache the current evaluation for the current frame
  52736. if (condition._evaluationId === currentRenderId) {
  52737. if (!condition._currentResult) {
  52738. return;
  52739. }
  52740. }
  52741. else {
  52742. condition._evaluationId = currentRenderId;
  52743. if (!condition.isValid()) {
  52744. condition._currentResult = false;
  52745. return;
  52746. }
  52747. condition._currentResult = true;
  52748. }
  52749. }
  52750. this.onBeforeExecuteObservable.notifyObservers(this);
  52751. this._nextActiveAction.execute(evt);
  52752. this.skipToNextActiveAction();
  52753. };
  52754. /**
  52755. * Execute placeholder for child classes
  52756. * @param evt optional action event
  52757. */
  52758. Action.prototype.execute = function (evt) {
  52759. };
  52760. /**
  52761. * Skips to next active action
  52762. */
  52763. Action.prototype.skipToNextActiveAction = function () {
  52764. if (this._nextActiveAction._child) {
  52765. if (!this._nextActiveAction._child._actionManager) {
  52766. this._nextActiveAction._child._actionManager = this._actionManager;
  52767. }
  52768. this._nextActiveAction = this._nextActiveAction._child;
  52769. }
  52770. else {
  52771. this._nextActiveAction = this;
  52772. }
  52773. };
  52774. /**
  52775. * Adds action to chain of actions, may be a DoNothingAction
  52776. * @param action defines the next action to execute
  52777. * @returns The action passed in
  52778. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52779. */
  52780. Action.prototype.then = function (action) {
  52781. this._child = action;
  52782. action._actionManager = this._actionManager;
  52783. action._prepare();
  52784. return action;
  52785. };
  52786. /**
  52787. * Internal only
  52788. * @hidden
  52789. */
  52790. Action.prototype._getProperty = function (propertyPath) {
  52791. return this._actionManager._getProperty(propertyPath);
  52792. };
  52793. /**
  52794. * Internal only
  52795. * @hidden
  52796. */
  52797. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52798. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52799. };
  52800. /**
  52801. * Serialize placeholder for child classes
  52802. * @param parent of child
  52803. * @returns the serialized object
  52804. */
  52805. Action.prototype.serialize = function (parent) {
  52806. };
  52807. /**
  52808. * Internal only called by serialize
  52809. * @hidden
  52810. */
  52811. Action.prototype._serialize = function (serializedAction, parent) {
  52812. var serializationObject = {
  52813. type: 1,
  52814. children: [],
  52815. name: serializedAction.name,
  52816. properties: serializedAction.properties || []
  52817. };
  52818. // Serialize child
  52819. if (this._child) {
  52820. this._child.serialize(serializationObject);
  52821. }
  52822. // Check if "this" has a condition
  52823. if (this._condition) {
  52824. var serializedCondition = this._condition.serialize();
  52825. serializedCondition.children.push(serializationObject);
  52826. if (parent) {
  52827. parent.children.push(serializedCondition);
  52828. }
  52829. return serializedCondition;
  52830. }
  52831. if (parent) {
  52832. parent.children.push(serializationObject);
  52833. }
  52834. return serializationObject;
  52835. };
  52836. /**
  52837. * Internal only
  52838. * @hidden
  52839. */
  52840. Action._SerializeValueAsString = function (value) {
  52841. if (typeof value === "number") {
  52842. return value.toString();
  52843. }
  52844. if (typeof value === "boolean") {
  52845. return value ? "true" : "false";
  52846. }
  52847. if (value instanceof BABYLON.Vector2) {
  52848. return value.x + ", " + value.y;
  52849. }
  52850. if (value instanceof BABYLON.Vector3) {
  52851. return value.x + ", " + value.y + ", " + value.z;
  52852. }
  52853. if (value instanceof BABYLON.Color3) {
  52854. return value.r + ", " + value.g + ", " + value.b;
  52855. }
  52856. if (value instanceof BABYLON.Color4) {
  52857. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52858. }
  52859. return value; // string
  52860. };
  52861. /**
  52862. * Internal only
  52863. * @hidden
  52864. */
  52865. Action._GetTargetProperty = function (target) {
  52866. return {
  52867. name: "target",
  52868. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52869. : target instanceof BABYLON.Light ? "LightProperties"
  52870. : target instanceof BABYLON.Camera ? "CameraProperties"
  52871. : "SceneProperties",
  52872. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52873. };
  52874. };
  52875. return Action;
  52876. }());
  52877. BABYLON.Action = Action;
  52878. })(BABYLON || (BABYLON = {}));
  52879. //# sourceMappingURL=babylon.action.js.map
  52880. var BABYLON;
  52881. (function (BABYLON) {
  52882. /**
  52883. * ActionEvent is the event being sent when an action is triggered.
  52884. */
  52885. var ActionEvent = /** @class */ (function () {
  52886. /**
  52887. * Creates a new ActionEvent
  52888. * @param source The mesh or sprite that triggered the action
  52889. * @param pointerX The X mouse cursor position at the time of the event
  52890. * @param pointerY The Y mouse cursor position at the time of the event
  52891. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52892. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52893. * @param additionalData additional data for the event
  52894. */
  52895. function ActionEvent(
  52896. /** The mesh or sprite that triggered the action */
  52897. source,
  52898. /** The X mouse cursor position at the time of the event */
  52899. pointerX,
  52900. /** The Y mouse cursor position at the time of the event */
  52901. pointerY,
  52902. /** The mesh that is currently pointed at (can be null) */
  52903. meshUnderPointer,
  52904. /** the original (browser) event that triggered the ActionEvent */
  52905. sourceEvent,
  52906. /** additional data for the event */
  52907. additionalData) {
  52908. this.source = source;
  52909. this.pointerX = pointerX;
  52910. this.pointerY = pointerY;
  52911. this.meshUnderPointer = meshUnderPointer;
  52912. this.sourceEvent = sourceEvent;
  52913. this.additionalData = additionalData;
  52914. }
  52915. /**
  52916. * Helper function to auto-create an ActionEvent from a source mesh.
  52917. * @param source The source mesh that triggered the event
  52918. * @param evt The original (browser) event
  52919. * @param additionalData additional data for the event
  52920. * @returns the new ActionEvent
  52921. */
  52922. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52923. var scene = source.getScene();
  52924. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52925. };
  52926. /**
  52927. * Helper function to auto-create an ActionEvent from a source sprite
  52928. * @param source The source sprite that triggered the event
  52929. * @param scene Scene associated with the sprite
  52930. * @param evt The original (browser) event
  52931. * @param additionalData additional data for the event
  52932. * @returns the new ActionEvent
  52933. */
  52934. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52935. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52936. };
  52937. /**
  52938. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52939. * @param scene the scene where the event occurred
  52940. * @param evt The original (browser) event
  52941. * @returns the new ActionEvent
  52942. */
  52943. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52944. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52945. };
  52946. /**
  52947. * Helper function to auto-create an ActionEvent from a primitive
  52948. * @param prim defines the target primitive
  52949. * @param pointerPos defines the pointer position
  52950. * @param evt The original (browser) event
  52951. * @param additionalData additional data for the event
  52952. * @returns the new ActionEvent
  52953. */
  52954. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52955. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52956. };
  52957. return ActionEvent;
  52958. }());
  52959. BABYLON.ActionEvent = ActionEvent;
  52960. /**
  52961. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52962. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52963. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52964. */
  52965. var ActionManager = /** @class */ (function () {
  52966. /**
  52967. * Creates a new action manager
  52968. * @param scene defines the hosting scene
  52969. */
  52970. function ActionManager(scene) {
  52971. // Members
  52972. /** Gets the list of actions */
  52973. this.actions = new Array();
  52974. /** Gets the cursor to use when hovering items */
  52975. this.hoverCursor = '';
  52976. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52977. scene.actionManagers.push(this);
  52978. }
  52979. Object.defineProperty(ActionManager, "NothingTrigger", {
  52980. /**
  52981. * Nothing
  52982. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52983. */
  52984. get: function () {
  52985. return ActionManager._NothingTrigger;
  52986. },
  52987. enumerable: true,
  52988. configurable: true
  52989. });
  52990. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52991. /**
  52992. * On pick
  52993. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52994. */
  52995. get: function () {
  52996. return ActionManager._OnPickTrigger;
  52997. },
  52998. enumerable: true,
  52999. configurable: true
  53000. });
  53001. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53002. /**
  53003. * On left pick
  53004. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53005. */
  53006. get: function () {
  53007. return ActionManager._OnLeftPickTrigger;
  53008. },
  53009. enumerable: true,
  53010. configurable: true
  53011. });
  53012. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53013. /**
  53014. * On right pick
  53015. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53016. */
  53017. get: function () {
  53018. return ActionManager._OnRightPickTrigger;
  53019. },
  53020. enumerable: true,
  53021. configurable: true
  53022. });
  53023. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53024. /**
  53025. * On center pick
  53026. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53027. */
  53028. get: function () {
  53029. return ActionManager._OnCenterPickTrigger;
  53030. },
  53031. enumerable: true,
  53032. configurable: true
  53033. });
  53034. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53035. /**
  53036. * On pick down
  53037. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53038. */
  53039. get: function () {
  53040. return ActionManager._OnPickDownTrigger;
  53041. },
  53042. enumerable: true,
  53043. configurable: true
  53044. });
  53045. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53046. /**
  53047. * On double pick
  53048. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53049. */
  53050. get: function () {
  53051. return ActionManager._OnDoublePickTrigger;
  53052. },
  53053. enumerable: true,
  53054. configurable: true
  53055. });
  53056. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53057. /**
  53058. * On pick up
  53059. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53060. */
  53061. get: function () {
  53062. return ActionManager._OnPickUpTrigger;
  53063. },
  53064. enumerable: true,
  53065. configurable: true
  53066. });
  53067. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53068. /**
  53069. * On pick out.
  53070. * This trigger will only be raised if you also declared a OnPickDown
  53071. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53072. */
  53073. get: function () {
  53074. return ActionManager._OnPickOutTrigger;
  53075. },
  53076. enumerable: true,
  53077. configurable: true
  53078. });
  53079. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53080. /**
  53081. * On long press
  53082. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53083. */
  53084. get: function () {
  53085. return ActionManager._OnLongPressTrigger;
  53086. },
  53087. enumerable: true,
  53088. configurable: true
  53089. });
  53090. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53091. /**
  53092. * On pointer over
  53093. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53094. */
  53095. get: function () {
  53096. return ActionManager._OnPointerOverTrigger;
  53097. },
  53098. enumerable: true,
  53099. configurable: true
  53100. });
  53101. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53102. /**
  53103. * On pointer out
  53104. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53105. */
  53106. get: function () {
  53107. return ActionManager._OnPointerOutTrigger;
  53108. },
  53109. enumerable: true,
  53110. configurable: true
  53111. });
  53112. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53113. /**
  53114. * On every frame
  53115. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53116. */
  53117. get: function () {
  53118. return ActionManager._OnEveryFrameTrigger;
  53119. },
  53120. enumerable: true,
  53121. configurable: true
  53122. });
  53123. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53124. /**
  53125. * On intersection enter
  53126. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53127. */
  53128. get: function () {
  53129. return ActionManager._OnIntersectionEnterTrigger;
  53130. },
  53131. enumerable: true,
  53132. configurable: true
  53133. });
  53134. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53135. /**
  53136. * On intersection exit
  53137. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53138. */
  53139. get: function () {
  53140. return ActionManager._OnIntersectionExitTrigger;
  53141. },
  53142. enumerable: true,
  53143. configurable: true
  53144. });
  53145. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53146. /**
  53147. * On key down
  53148. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53149. */
  53150. get: function () {
  53151. return ActionManager._OnKeyDownTrigger;
  53152. },
  53153. enumerable: true,
  53154. configurable: true
  53155. });
  53156. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53157. /**
  53158. * On key up
  53159. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53160. */
  53161. get: function () {
  53162. return ActionManager._OnKeyUpTrigger;
  53163. },
  53164. enumerable: true,
  53165. configurable: true
  53166. });
  53167. // Methods
  53168. /**
  53169. * Releases all associated resources
  53170. */
  53171. ActionManager.prototype.dispose = function () {
  53172. var index = this._scene.actionManagers.indexOf(this);
  53173. for (var i = 0; i < this.actions.length; i++) {
  53174. var action = this.actions[i];
  53175. ActionManager.Triggers[action.trigger]--;
  53176. if (ActionManager.Triggers[action.trigger] === 0) {
  53177. delete ActionManager.Triggers[action.trigger];
  53178. }
  53179. }
  53180. if (index > -1) {
  53181. this._scene.actionManagers.splice(index, 1);
  53182. }
  53183. };
  53184. /**
  53185. * Gets hosting scene
  53186. * @returns the hosting scene
  53187. */
  53188. ActionManager.prototype.getScene = function () {
  53189. return this._scene;
  53190. };
  53191. /**
  53192. * Does this action manager handles actions of any of the given triggers
  53193. * @param triggers defines the triggers to be tested
  53194. * @return a boolean indicating whether one (or more) of the triggers is handled
  53195. */
  53196. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53197. for (var index = 0; index < this.actions.length; index++) {
  53198. var action = this.actions[index];
  53199. if (triggers.indexOf(action.trigger) > -1) {
  53200. return true;
  53201. }
  53202. }
  53203. return false;
  53204. };
  53205. /**
  53206. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  53207. * speed.
  53208. * @param triggerA defines the trigger to be tested
  53209. * @param triggerB defines the trigger to be tested
  53210. * @return a boolean indicating whether one (or more) of the triggers is handled
  53211. */
  53212. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  53213. for (var index = 0; index < this.actions.length; index++) {
  53214. var action = this.actions[index];
  53215. if (triggerA == action.trigger || triggerB == action.trigger) {
  53216. return true;
  53217. }
  53218. }
  53219. return false;
  53220. };
  53221. /**
  53222. * Does this action manager handles actions of a given trigger
  53223. * @param trigger defines the trigger to be tested
  53224. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53225. * @return whether the trigger is handled
  53226. */
  53227. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53228. for (var index = 0; index < this.actions.length; index++) {
  53229. var action = this.actions[index];
  53230. if (action.trigger === trigger) {
  53231. if (parameterPredicate) {
  53232. if (parameterPredicate(action.getTriggerParameter())) {
  53233. return true;
  53234. }
  53235. }
  53236. else {
  53237. return true;
  53238. }
  53239. }
  53240. }
  53241. return false;
  53242. };
  53243. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53244. /**
  53245. * Does this action manager has pointer triggers
  53246. */
  53247. get: function () {
  53248. for (var index = 0; index < this.actions.length; index++) {
  53249. var action = this.actions[index];
  53250. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53251. return true;
  53252. }
  53253. }
  53254. return false;
  53255. },
  53256. enumerable: true,
  53257. configurable: true
  53258. });
  53259. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53260. /**
  53261. * Does this action manager has pick triggers
  53262. */
  53263. get: function () {
  53264. for (var index = 0; index < this.actions.length; index++) {
  53265. var action = this.actions[index];
  53266. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53267. return true;
  53268. }
  53269. }
  53270. return false;
  53271. },
  53272. enumerable: true,
  53273. configurable: true
  53274. });
  53275. Object.defineProperty(ActionManager, "HasTriggers", {
  53276. /**
  53277. * Does exist one action manager with at least one trigger
  53278. **/
  53279. get: function () {
  53280. for (var t in ActionManager.Triggers) {
  53281. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53282. return true;
  53283. }
  53284. }
  53285. return false;
  53286. },
  53287. enumerable: true,
  53288. configurable: true
  53289. });
  53290. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53291. /**
  53292. * Does exist one action manager with at least one pick trigger
  53293. **/
  53294. get: function () {
  53295. for (var t in ActionManager.Triggers) {
  53296. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53297. var t_int = parseInt(t);
  53298. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53299. return true;
  53300. }
  53301. }
  53302. }
  53303. return false;
  53304. },
  53305. enumerable: true,
  53306. configurable: true
  53307. });
  53308. /**
  53309. * Does exist one action manager that handles actions of a given trigger
  53310. * @param trigger defines the trigger to be tested
  53311. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53312. **/
  53313. ActionManager.HasSpecificTrigger = function (trigger) {
  53314. for (var t in ActionManager.Triggers) {
  53315. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53316. var t_int = parseInt(t);
  53317. if (t_int === trigger) {
  53318. return true;
  53319. }
  53320. }
  53321. }
  53322. return false;
  53323. };
  53324. /**
  53325. * Registers an action to this action manager
  53326. * @param action defines the action to be registered
  53327. * @return the action amended (prepared) after registration
  53328. */
  53329. ActionManager.prototype.registerAction = function (action) {
  53330. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53331. if (this.getScene().actionManager !== this) {
  53332. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53333. return null;
  53334. }
  53335. }
  53336. this.actions.push(action);
  53337. if (ActionManager.Triggers[action.trigger]) {
  53338. ActionManager.Triggers[action.trigger]++;
  53339. }
  53340. else {
  53341. ActionManager.Triggers[action.trigger] = 1;
  53342. }
  53343. action._actionManager = this;
  53344. action._prepare();
  53345. return action;
  53346. };
  53347. /**
  53348. * Unregisters an action to this action manager
  53349. * @param action defines the action to be unregistered
  53350. * @return a boolean indicating whether the action has been unregistered
  53351. */
  53352. ActionManager.prototype.unregisterAction = function (action) {
  53353. var index = this.actions.indexOf(action);
  53354. if (index !== -1) {
  53355. this.actions.splice(index, 1);
  53356. ActionManager.Triggers[action.trigger] -= 1;
  53357. if (ActionManager.Triggers[action.trigger] === 0) {
  53358. delete ActionManager.Triggers[action.trigger];
  53359. }
  53360. delete action._actionManager;
  53361. return true;
  53362. }
  53363. return false;
  53364. };
  53365. /**
  53366. * Process a specific trigger
  53367. * @param trigger defines the trigger to process
  53368. * @param evt defines the event details to be processed
  53369. */
  53370. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53371. for (var index = 0; index < this.actions.length; index++) {
  53372. var action = this.actions[index];
  53373. if (action.trigger === trigger) {
  53374. if (evt) {
  53375. if (trigger === ActionManager.OnKeyUpTrigger
  53376. || trigger === ActionManager.OnKeyDownTrigger) {
  53377. var parameter = action.getTriggerParameter();
  53378. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53379. if (!parameter.toLowerCase) {
  53380. continue;
  53381. }
  53382. var lowerCase = parameter.toLowerCase();
  53383. if (lowerCase !== evt.sourceEvent.key) {
  53384. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53385. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53386. if (actualkey !== lowerCase) {
  53387. continue;
  53388. }
  53389. }
  53390. }
  53391. }
  53392. }
  53393. action._executeCurrent(evt);
  53394. }
  53395. }
  53396. };
  53397. /** @hidden */
  53398. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53399. var properties = propertyPath.split(".");
  53400. for (var index = 0; index < properties.length - 1; index++) {
  53401. target = target[properties[index]];
  53402. }
  53403. return target;
  53404. };
  53405. /** @hidden */
  53406. ActionManager.prototype._getProperty = function (propertyPath) {
  53407. var properties = propertyPath.split(".");
  53408. return properties[properties.length - 1];
  53409. };
  53410. /**
  53411. * Serialize this manager to a JSON object
  53412. * @param name defines the property name to store this manager
  53413. * @returns a JSON representation of this manager
  53414. */
  53415. ActionManager.prototype.serialize = function (name) {
  53416. var root = {
  53417. children: new Array(),
  53418. name: name,
  53419. type: 3,
  53420. properties: new Array() // Empty for root but required
  53421. };
  53422. for (var i = 0; i < this.actions.length; i++) {
  53423. var triggerObject = {
  53424. type: 0,
  53425. children: new Array(),
  53426. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53427. properties: new Array()
  53428. };
  53429. var triggerOptions = this.actions[i].triggerOptions;
  53430. if (triggerOptions && typeof triggerOptions !== "number") {
  53431. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53432. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53433. }
  53434. else {
  53435. var parameter = {};
  53436. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53437. if (triggerOptions.parameter.mesh) {
  53438. parameter._meshId = triggerOptions.parameter.mesh.id;
  53439. }
  53440. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53441. }
  53442. }
  53443. // Serialize child action, recursively
  53444. this.actions[i].serialize(triggerObject);
  53445. // Add serialized trigger
  53446. root.children.push(triggerObject);
  53447. }
  53448. return root;
  53449. };
  53450. /**
  53451. * Creates a new ActionManager from a JSON data
  53452. * @param parsedActions defines the JSON data to read from
  53453. * @param object defines the hosting mesh
  53454. * @param scene defines the hosting scene
  53455. */
  53456. ActionManager.Parse = function (parsedActions, object, scene) {
  53457. var actionManager = new ActionManager(scene);
  53458. if (object === null)
  53459. scene.actionManager = actionManager;
  53460. else
  53461. object.actionManager = actionManager;
  53462. // instanciate a new object
  53463. var instanciate = function (name, params) {
  53464. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53465. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53466. newInstance.constructor.apply(newInstance, params);
  53467. return newInstance;
  53468. };
  53469. var parseParameter = function (name, value, target, propertyPath) {
  53470. if (propertyPath === null) {
  53471. // String, boolean or float
  53472. var floatValue = parseFloat(value);
  53473. if (value === "true" || value === "false")
  53474. return value === "true";
  53475. else
  53476. return isNaN(floatValue) ? value : floatValue;
  53477. }
  53478. var effectiveTarget = propertyPath.split(".");
  53479. var values = value.split(",");
  53480. // Get effective Target
  53481. for (var i = 0; i < effectiveTarget.length; i++) {
  53482. target = target[effectiveTarget[i]];
  53483. }
  53484. // Return appropriate value with its type
  53485. if (typeof (target) === "boolean")
  53486. return values[0] === "true";
  53487. if (typeof (target) === "string")
  53488. return values[0];
  53489. // Parameters with multiple values such as Vector3 etc.
  53490. var split = new Array();
  53491. for (var i = 0; i < values.length; i++)
  53492. split.push(parseFloat(values[i]));
  53493. if (target instanceof BABYLON.Vector3)
  53494. return BABYLON.Vector3.FromArray(split);
  53495. if (target instanceof BABYLON.Vector4)
  53496. return BABYLON.Vector4.FromArray(split);
  53497. if (target instanceof BABYLON.Color3)
  53498. return BABYLON.Color3.FromArray(split);
  53499. if (target instanceof BABYLON.Color4)
  53500. return BABYLON.Color4.FromArray(split);
  53501. return parseFloat(values[0]);
  53502. };
  53503. // traverse graph per trigger
  53504. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53505. if (combineArray === void 0) { combineArray = null; }
  53506. if (parsedAction.detached)
  53507. return;
  53508. var parameters = new Array();
  53509. var target = null;
  53510. var propertyPath = null;
  53511. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53512. // Parameters
  53513. if (parsedAction.type === 2)
  53514. parameters.push(actionManager);
  53515. else
  53516. parameters.push(trigger);
  53517. if (combine) {
  53518. var actions = new Array();
  53519. for (var j = 0; j < parsedAction.combine.length; j++) {
  53520. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53521. }
  53522. parameters.push(actions);
  53523. }
  53524. else {
  53525. for (var i = 0; i < parsedAction.properties.length; i++) {
  53526. var value = parsedAction.properties[i].value;
  53527. var name = parsedAction.properties[i].name;
  53528. var targetType = parsedAction.properties[i].targetType;
  53529. if (name === "target")
  53530. if (targetType !== null && targetType === "SceneProperties")
  53531. value = target = scene;
  53532. else
  53533. value = target = scene.getNodeByName(value);
  53534. else if (name === "parent")
  53535. value = scene.getNodeByName(value);
  53536. else if (name === "sound")
  53537. value = scene.getSoundByName(value);
  53538. else if (name !== "propertyPath") {
  53539. if (parsedAction.type === 2 && name === "operator")
  53540. value = BABYLON.ValueCondition[value];
  53541. else
  53542. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53543. }
  53544. else {
  53545. propertyPath = value;
  53546. }
  53547. parameters.push(value);
  53548. }
  53549. }
  53550. if (combineArray === null) {
  53551. parameters.push(condition);
  53552. }
  53553. else {
  53554. parameters.push(null);
  53555. }
  53556. // If interpolate value action
  53557. if (parsedAction.name === "InterpolateValueAction") {
  53558. var param = parameters[parameters.length - 2];
  53559. parameters[parameters.length - 1] = param;
  53560. parameters[parameters.length - 2] = condition;
  53561. }
  53562. // Action or condition(s) and not CombineAction
  53563. var newAction = instanciate(parsedAction.name, parameters);
  53564. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53565. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53566. if (action)
  53567. action.then(nothing);
  53568. else
  53569. actionManager.registerAction(nothing);
  53570. action = nothing;
  53571. }
  53572. if (combineArray === null) {
  53573. if (newAction instanceof BABYLON.Condition) {
  53574. condition = newAction;
  53575. newAction = action;
  53576. }
  53577. else {
  53578. condition = null;
  53579. if (action)
  53580. action.then(newAction);
  53581. else
  53582. actionManager.registerAction(newAction);
  53583. }
  53584. }
  53585. else {
  53586. combineArray.push(newAction);
  53587. }
  53588. for (var i = 0; i < parsedAction.children.length; i++)
  53589. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53590. };
  53591. // triggers
  53592. for (var i = 0; i < parsedActions.children.length; i++) {
  53593. var triggerParams;
  53594. var trigger = parsedActions.children[i];
  53595. if (trigger.properties.length > 0) {
  53596. var param = trigger.properties[0].value;
  53597. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53598. if (value._meshId) {
  53599. value.mesh = scene.getMeshByID(value._meshId);
  53600. }
  53601. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53602. }
  53603. else
  53604. triggerParams = ActionManager[trigger.name];
  53605. for (var j = 0; j < trigger.children.length; j++) {
  53606. if (!trigger.detached)
  53607. traverse(trigger.children[j], triggerParams, null, null);
  53608. }
  53609. }
  53610. };
  53611. /**
  53612. * Get a trigger name by index
  53613. * @param trigger defines the trigger index
  53614. * @returns a trigger name
  53615. */
  53616. ActionManager.GetTriggerName = function (trigger) {
  53617. switch (trigger) {
  53618. case 0: return "NothingTrigger";
  53619. case 1: return "OnPickTrigger";
  53620. case 2: return "OnLeftPickTrigger";
  53621. case 3: return "OnRightPickTrigger";
  53622. case 4: return "OnCenterPickTrigger";
  53623. case 5: return "OnPickDownTrigger";
  53624. case 6: return "OnPickUpTrigger";
  53625. case 7: return "OnLongPressTrigger";
  53626. case 8: return "OnPointerOverTrigger";
  53627. case 9: return "OnPointerOutTrigger";
  53628. case 10: return "OnEveryFrameTrigger";
  53629. case 11: return "OnIntersectionEnterTrigger";
  53630. case 12: return "OnIntersectionExitTrigger";
  53631. case 13: return "OnKeyDownTrigger";
  53632. case 14: return "OnKeyUpTrigger";
  53633. case 15: return "OnPickOutTrigger";
  53634. default: return "";
  53635. }
  53636. };
  53637. // Statics
  53638. ActionManager._NothingTrigger = 0;
  53639. ActionManager._OnPickTrigger = 1;
  53640. ActionManager._OnLeftPickTrigger = 2;
  53641. ActionManager._OnRightPickTrigger = 3;
  53642. ActionManager._OnCenterPickTrigger = 4;
  53643. ActionManager._OnPickDownTrigger = 5;
  53644. ActionManager._OnDoublePickTrigger = 6;
  53645. ActionManager._OnPickUpTrigger = 7;
  53646. ActionManager._OnLongPressTrigger = 8;
  53647. ActionManager._OnPointerOverTrigger = 9;
  53648. ActionManager._OnPointerOutTrigger = 10;
  53649. ActionManager._OnEveryFrameTrigger = 11;
  53650. ActionManager._OnIntersectionEnterTrigger = 12;
  53651. ActionManager._OnIntersectionExitTrigger = 13;
  53652. ActionManager._OnKeyDownTrigger = 14;
  53653. ActionManager._OnKeyUpTrigger = 15;
  53654. ActionManager._OnPickOutTrigger = 16;
  53655. /** Gets the list of active triggers */
  53656. ActionManager.Triggers = {};
  53657. return ActionManager;
  53658. }());
  53659. BABYLON.ActionManager = ActionManager;
  53660. })(BABYLON || (BABYLON = {}));
  53661. //# sourceMappingURL=babylon.actionManager.js.map
  53662. var BABYLON;
  53663. (function (BABYLON) {
  53664. var InterpolateValueAction = /** @class */ (function (_super) {
  53665. __extends(InterpolateValueAction, _super);
  53666. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53667. if (duration === void 0) { duration = 1000; }
  53668. var _this = _super.call(this, triggerOptions, condition) || this;
  53669. _this.propertyPath = propertyPath;
  53670. _this.value = value;
  53671. _this.duration = duration;
  53672. _this.stopOtherAnimations = stopOtherAnimations;
  53673. _this.onInterpolationDone = onInterpolationDone;
  53674. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53675. _this._target = _this._effectiveTarget = target;
  53676. return _this;
  53677. }
  53678. /** @hidden */
  53679. InterpolateValueAction.prototype._prepare = function () {
  53680. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53681. this._property = this._getProperty(this.propertyPath);
  53682. };
  53683. InterpolateValueAction.prototype.execute = function () {
  53684. var _this = this;
  53685. var scene = this._actionManager.getScene();
  53686. var keys = [
  53687. {
  53688. frame: 0,
  53689. value: this._effectiveTarget[this._property]
  53690. }, {
  53691. frame: 100,
  53692. value: this.value
  53693. }
  53694. ];
  53695. var dataType;
  53696. if (typeof this.value === "number") {
  53697. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53698. }
  53699. else if (this.value instanceof BABYLON.Color3) {
  53700. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53701. }
  53702. else if (this.value instanceof BABYLON.Vector3) {
  53703. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53704. }
  53705. else if (this.value instanceof BABYLON.Matrix) {
  53706. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53707. }
  53708. else if (this.value instanceof BABYLON.Quaternion) {
  53709. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53710. }
  53711. else {
  53712. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53713. return;
  53714. }
  53715. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53716. animation.setKeys(keys);
  53717. if (this.stopOtherAnimations) {
  53718. scene.stopAnimation(this._effectiveTarget);
  53719. }
  53720. var wrapper = function () {
  53721. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53722. if (_this.onInterpolationDone) {
  53723. _this.onInterpolationDone();
  53724. }
  53725. };
  53726. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53727. };
  53728. InterpolateValueAction.prototype.serialize = function (parent) {
  53729. return _super.prototype._serialize.call(this, {
  53730. name: "InterpolateValueAction",
  53731. properties: [
  53732. BABYLON.Action._GetTargetProperty(this._target),
  53733. { name: "propertyPath", value: this.propertyPath },
  53734. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53735. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53736. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53737. ]
  53738. }, parent);
  53739. };
  53740. return InterpolateValueAction;
  53741. }(BABYLON.Action));
  53742. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53743. })(BABYLON || (BABYLON = {}));
  53744. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53745. var BABYLON;
  53746. (function (BABYLON) {
  53747. var SwitchBooleanAction = /** @class */ (function (_super) {
  53748. __extends(SwitchBooleanAction, _super);
  53749. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53750. var _this = _super.call(this, triggerOptions, condition) || this;
  53751. _this.propertyPath = propertyPath;
  53752. _this._target = _this._effectiveTarget = target;
  53753. return _this;
  53754. }
  53755. /** @hidden */
  53756. SwitchBooleanAction.prototype._prepare = function () {
  53757. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53758. this._property = this._getProperty(this.propertyPath);
  53759. };
  53760. SwitchBooleanAction.prototype.execute = function () {
  53761. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53762. };
  53763. SwitchBooleanAction.prototype.serialize = function (parent) {
  53764. return _super.prototype._serialize.call(this, {
  53765. name: "SwitchBooleanAction",
  53766. properties: [
  53767. BABYLON.Action._GetTargetProperty(this._target),
  53768. { name: "propertyPath", value: this.propertyPath }
  53769. ]
  53770. }, parent);
  53771. };
  53772. return SwitchBooleanAction;
  53773. }(BABYLON.Action));
  53774. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53775. var SetStateAction = /** @class */ (function (_super) {
  53776. __extends(SetStateAction, _super);
  53777. function SetStateAction(triggerOptions, target, value, condition) {
  53778. var _this = _super.call(this, triggerOptions, condition) || this;
  53779. _this.value = value;
  53780. _this._target = target;
  53781. return _this;
  53782. }
  53783. SetStateAction.prototype.execute = function () {
  53784. this._target.state = this.value;
  53785. };
  53786. SetStateAction.prototype.serialize = function (parent) {
  53787. return _super.prototype._serialize.call(this, {
  53788. name: "SetStateAction",
  53789. properties: [
  53790. BABYLON.Action._GetTargetProperty(this._target),
  53791. { name: "value", value: this.value }
  53792. ]
  53793. }, parent);
  53794. };
  53795. return SetStateAction;
  53796. }(BABYLON.Action));
  53797. BABYLON.SetStateAction = SetStateAction;
  53798. var SetValueAction = /** @class */ (function (_super) {
  53799. __extends(SetValueAction, _super);
  53800. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53801. var _this = _super.call(this, triggerOptions, condition) || this;
  53802. _this.propertyPath = propertyPath;
  53803. _this.value = value;
  53804. _this._target = _this._effectiveTarget = target;
  53805. return _this;
  53806. }
  53807. /** @hidden */
  53808. SetValueAction.prototype._prepare = function () {
  53809. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53810. this._property = this._getProperty(this.propertyPath);
  53811. };
  53812. SetValueAction.prototype.execute = function () {
  53813. this._effectiveTarget[this._property] = this.value;
  53814. if (this._target.markAsDirty) {
  53815. this._target.markAsDirty(this._property);
  53816. }
  53817. };
  53818. SetValueAction.prototype.serialize = function (parent) {
  53819. return _super.prototype._serialize.call(this, {
  53820. name: "SetValueAction",
  53821. properties: [
  53822. BABYLON.Action._GetTargetProperty(this._target),
  53823. { name: "propertyPath", value: this.propertyPath },
  53824. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53825. ]
  53826. }, parent);
  53827. };
  53828. return SetValueAction;
  53829. }(BABYLON.Action));
  53830. BABYLON.SetValueAction = SetValueAction;
  53831. var IncrementValueAction = /** @class */ (function (_super) {
  53832. __extends(IncrementValueAction, _super);
  53833. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53834. var _this = _super.call(this, triggerOptions, condition) || this;
  53835. _this.propertyPath = propertyPath;
  53836. _this.value = value;
  53837. _this._target = _this._effectiveTarget = target;
  53838. return _this;
  53839. }
  53840. /** @hidden */
  53841. IncrementValueAction.prototype._prepare = function () {
  53842. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53843. this._property = this._getProperty(this.propertyPath);
  53844. if (typeof this._effectiveTarget[this._property] !== "number") {
  53845. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53846. }
  53847. };
  53848. IncrementValueAction.prototype.execute = function () {
  53849. this._effectiveTarget[this._property] += this.value;
  53850. if (this._target.markAsDirty) {
  53851. this._target.markAsDirty(this._property);
  53852. }
  53853. };
  53854. IncrementValueAction.prototype.serialize = function (parent) {
  53855. return _super.prototype._serialize.call(this, {
  53856. name: "IncrementValueAction",
  53857. properties: [
  53858. BABYLON.Action._GetTargetProperty(this._target),
  53859. { name: "propertyPath", value: this.propertyPath },
  53860. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53861. ]
  53862. }, parent);
  53863. };
  53864. return IncrementValueAction;
  53865. }(BABYLON.Action));
  53866. BABYLON.IncrementValueAction = IncrementValueAction;
  53867. var PlayAnimationAction = /** @class */ (function (_super) {
  53868. __extends(PlayAnimationAction, _super);
  53869. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53870. var _this = _super.call(this, triggerOptions, condition) || this;
  53871. _this.from = from;
  53872. _this.to = to;
  53873. _this.loop = loop;
  53874. _this._target = target;
  53875. return _this;
  53876. }
  53877. /** @hidden */
  53878. PlayAnimationAction.prototype._prepare = function () {
  53879. };
  53880. PlayAnimationAction.prototype.execute = function () {
  53881. var scene = this._actionManager.getScene();
  53882. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53883. };
  53884. PlayAnimationAction.prototype.serialize = function (parent) {
  53885. return _super.prototype._serialize.call(this, {
  53886. name: "PlayAnimationAction",
  53887. properties: [
  53888. BABYLON.Action._GetTargetProperty(this._target),
  53889. { name: "from", value: String(this.from) },
  53890. { name: "to", value: String(this.to) },
  53891. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53892. ]
  53893. }, parent);
  53894. };
  53895. return PlayAnimationAction;
  53896. }(BABYLON.Action));
  53897. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53898. var StopAnimationAction = /** @class */ (function (_super) {
  53899. __extends(StopAnimationAction, _super);
  53900. function StopAnimationAction(triggerOptions, target, condition) {
  53901. var _this = _super.call(this, triggerOptions, condition) || this;
  53902. _this._target = target;
  53903. return _this;
  53904. }
  53905. /** @hidden */
  53906. StopAnimationAction.prototype._prepare = function () {
  53907. };
  53908. StopAnimationAction.prototype.execute = function () {
  53909. var scene = this._actionManager.getScene();
  53910. scene.stopAnimation(this._target);
  53911. };
  53912. StopAnimationAction.prototype.serialize = function (parent) {
  53913. return _super.prototype._serialize.call(this, {
  53914. name: "StopAnimationAction",
  53915. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53916. }, parent);
  53917. };
  53918. return StopAnimationAction;
  53919. }(BABYLON.Action));
  53920. BABYLON.StopAnimationAction = StopAnimationAction;
  53921. var DoNothingAction = /** @class */ (function (_super) {
  53922. __extends(DoNothingAction, _super);
  53923. function DoNothingAction(triggerOptions, condition) {
  53924. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53925. return _super.call(this, triggerOptions, condition) || this;
  53926. }
  53927. DoNothingAction.prototype.execute = function () {
  53928. };
  53929. DoNothingAction.prototype.serialize = function (parent) {
  53930. return _super.prototype._serialize.call(this, {
  53931. name: "DoNothingAction",
  53932. properties: []
  53933. }, parent);
  53934. };
  53935. return DoNothingAction;
  53936. }(BABYLON.Action));
  53937. BABYLON.DoNothingAction = DoNothingAction;
  53938. var CombineAction = /** @class */ (function (_super) {
  53939. __extends(CombineAction, _super);
  53940. function CombineAction(triggerOptions, children, condition) {
  53941. var _this = _super.call(this, triggerOptions, condition) || this;
  53942. _this.children = children;
  53943. return _this;
  53944. }
  53945. /** @hidden */
  53946. CombineAction.prototype._prepare = function () {
  53947. for (var index = 0; index < this.children.length; index++) {
  53948. this.children[index]._actionManager = this._actionManager;
  53949. this.children[index]._prepare();
  53950. }
  53951. };
  53952. CombineAction.prototype.execute = function (evt) {
  53953. for (var index = 0; index < this.children.length; index++) {
  53954. this.children[index].execute(evt);
  53955. }
  53956. };
  53957. CombineAction.prototype.serialize = function (parent) {
  53958. var serializationObject = _super.prototype._serialize.call(this, {
  53959. name: "CombineAction",
  53960. properties: [],
  53961. combine: []
  53962. }, parent);
  53963. for (var i = 0; i < this.children.length; i++) {
  53964. serializationObject.combine.push(this.children[i].serialize(null));
  53965. }
  53966. return serializationObject;
  53967. };
  53968. return CombineAction;
  53969. }(BABYLON.Action));
  53970. BABYLON.CombineAction = CombineAction;
  53971. var ExecuteCodeAction = /** @class */ (function (_super) {
  53972. __extends(ExecuteCodeAction, _super);
  53973. function ExecuteCodeAction(triggerOptions, func, condition) {
  53974. var _this = _super.call(this, triggerOptions, condition) || this;
  53975. _this.func = func;
  53976. return _this;
  53977. }
  53978. ExecuteCodeAction.prototype.execute = function (evt) {
  53979. this.func(evt);
  53980. };
  53981. return ExecuteCodeAction;
  53982. }(BABYLON.Action));
  53983. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53984. var SetParentAction = /** @class */ (function (_super) {
  53985. __extends(SetParentAction, _super);
  53986. function SetParentAction(triggerOptions, target, parent, condition) {
  53987. var _this = _super.call(this, triggerOptions, condition) || this;
  53988. _this._target = target;
  53989. _this._parent = parent;
  53990. return _this;
  53991. }
  53992. /** @hidden */
  53993. SetParentAction.prototype._prepare = function () {
  53994. };
  53995. SetParentAction.prototype.execute = function () {
  53996. if (this._target.parent === this._parent) {
  53997. return;
  53998. }
  53999. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54000. invertParentWorldMatrix.invert();
  54001. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54002. this._target.parent = this._parent;
  54003. };
  54004. SetParentAction.prototype.serialize = function (parent) {
  54005. return _super.prototype._serialize.call(this, {
  54006. name: "SetParentAction",
  54007. properties: [
  54008. BABYLON.Action._GetTargetProperty(this._target),
  54009. BABYLON.Action._GetTargetProperty(this._parent),
  54010. ]
  54011. }, parent);
  54012. };
  54013. return SetParentAction;
  54014. }(BABYLON.Action));
  54015. BABYLON.SetParentAction = SetParentAction;
  54016. var PlaySoundAction = /** @class */ (function (_super) {
  54017. __extends(PlaySoundAction, _super);
  54018. function PlaySoundAction(triggerOptions, sound, condition) {
  54019. var _this = _super.call(this, triggerOptions, condition) || this;
  54020. _this._sound = sound;
  54021. return _this;
  54022. }
  54023. /** @hidden */
  54024. PlaySoundAction.prototype._prepare = function () {
  54025. };
  54026. PlaySoundAction.prototype.execute = function () {
  54027. if (this._sound !== undefined)
  54028. this._sound.play();
  54029. };
  54030. PlaySoundAction.prototype.serialize = function (parent) {
  54031. return _super.prototype._serialize.call(this, {
  54032. name: "PlaySoundAction",
  54033. properties: [{ name: "sound", value: this._sound.name }]
  54034. }, parent);
  54035. };
  54036. return PlaySoundAction;
  54037. }(BABYLON.Action));
  54038. BABYLON.PlaySoundAction = PlaySoundAction;
  54039. var StopSoundAction = /** @class */ (function (_super) {
  54040. __extends(StopSoundAction, _super);
  54041. function StopSoundAction(triggerOptions, sound, condition) {
  54042. var _this = _super.call(this, triggerOptions, condition) || this;
  54043. _this._sound = sound;
  54044. return _this;
  54045. }
  54046. /** @hidden */
  54047. StopSoundAction.prototype._prepare = function () {
  54048. };
  54049. StopSoundAction.prototype.execute = function () {
  54050. if (this._sound !== undefined)
  54051. this._sound.stop();
  54052. };
  54053. StopSoundAction.prototype.serialize = function (parent) {
  54054. return _super.prototype._serialize.call(this, {
  54055. name: "StopSoundAction",
  54056. properties: [{ name: "sound", value: this._sound.name }]
  54057. }, parent);
  54058. };
  54059. return StopSoundAction;
  54060. }(BABYLON.Action));
  54061. BABYLON.StopSoundAction = StopSoundAction;
  54062. })(BABYLON || (BABYLON = {}));
  54063. //# sourceMappingURL=babylon.directActions.js.map
  54064. var BABYLON;
  54065. (function (BABYLON) {
  54066. var SpriteManager = /** @class */ (function () {
  54067. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54068. if (epsilon === void 0) { epsilon = 0.01; }
  54069. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54070. this.name = name;
  54071. this.sprites = new Array();
  54072. this.renderingGroupId = 0;
  54073. this.layerMask = 0x0FFFFFFF;
  54074. this.fogEnabled = true;
  54075. this.isPickable = false;
  54076. /**
  54077. * An event triggered when the manager is disposed.
  54078. */
  54079. this.onDisposeObservable = new BABYLON.Observable();
  54080. this._vertexBuffers = {};
  54081. this._capacity = capacity;
  54082. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54083. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54084. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54085. if (cellSize.width && cellSize.height) {
  54086. this.cellWidth = cellSize.width;
  54087. this.cellHeight = cellSize.height;
  54088. }
  54089. else if (cellSize !== undefined) {
  54090. this.cellWidth = cellSize;
  54091. this.cellHeight = cellSize;
  54092. }
  54093. else {
  54094. return;
  54095. }
  54096. this._epsilon = epsilon;
  54097. this._scene = scene;
  54098. this._scene.spriteManagers.push(this);
  54099. var indices = [];
  54100. var index = 0;
  54101. for (var count = 0; count < capacity; count++) {
  54102. indices.push(index);
  54103. indices.push(index + 1);
  54104. indices.push(index + 2);
  54105. indices.push(index);
  54106. indices.push(index + 2);
  54107. indices.push(index + 3);
  54108. index += 4;
  54109. }
  54110. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54111. // VBO
  54112. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54113. this._vertexData = new Float32Array(capacity * 16 * 4);
  54114. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54115. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54116. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54117. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54118. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54119. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54120. this._vertexBuffers["options"] = options;
  54121. this._vertexBuffers["cellInfo"] = cellInfo;
  54122. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54123. // Effects
  54124. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54125. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54126. }
  54127. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54128. set: function (callback) {
  54129. if (this._onDisposeObserver) {
  54130. this.onDisposeObservable.remove(this._onDisposeObserver);
  54131. }
  54132. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54133. },
  54134. enumerable: true,
  54135. configurable: true
  54136. });
  54137. Object.defineProperty(SpriteManager.prototype, "texture", {
  54138. get: function () {
  54139. return this._spriteTexture;
  54140. },
  54141. set: function (value) {
  54142. this._spriteTexture = value;
  54143. },
  54144. enumerable: true,
  54145. configurable: true
  54146. });
  54147. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54148. var arrayOffset = index * 16;
  54149. if (offsetX === 0)
  54150. offsetX = this._epsilon;
  54151. else if (offsetX === 1)
  54152. offsetX = 1 - this._epsilon;
  54153. if (offsetY === 0)
  54154. offsetY = this._epsilon;
  54155. else if (offsetY === 1)
  54156. offsetY = 1 - this._epsilon;
  54157. this._vertexData[arrayOffset] = sprite.position.x;
  54158. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54159. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54160. this._vertexData[arrayOffset + 3] = sprite.angle;
  54161. this._vertexData[arrayOffset + 4] = sprite.width;
  54162. this._vertexData[arrayOffset + 5] = sprite.height;
  54163. this._vertexData[arrayOffset + 6] = offsetX;
  54164. this._vertexData[arrayOffset + 7] = offsetY;
  54165. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54166. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54167. var offset = (sprite.cellIndex / rowSize) >> 0;
  54168. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54169. this._vertexData[arrayOffset + 11] = offset;
  54170. // Color
  54171. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54172. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54173. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54174. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54175. };
  54176. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54177. var count = Math.min(this._capacity, this.sprites.length);
  54178. var min = BABYLON.Vector3.Zero();
  54179. var max = BABYLON.Vector3.Zero();
  54180. var distance = Number.MAX_VALUE;
  54181. var currentSprite = null;
  54182. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54183. var cameraView = camera.getViewMatrix();
  54184. for (var index = 0; index < count; index++) {
  54185. var sprite = this.sprites[index];
  54186. if (!sprite) {
  54187. continue;
  54188. }
  54189. if (predicate) {
  54190. if (!predicate(sprite)) {
  54191. continue;
  54192. }
  54193. }
  54194. else if (!sprite.isPickable) {
  54195. continue;
  54196. }
  54197. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54198. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54199. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54200. if (ray.intersectsBoxMinMax(min, max)) {
  54201. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54202. if (distance > currentDistance) {
  54203. distance = currentDistance;
  54204. currentSprite = sprite;
  54205. if (fastCheck) {
  54206. break;
  54207. }
  54208. }
  54209. }
  54210. }
  54211. if (currentSprite) {
  54212. var result = new BABYLON.PickingInfo();
  54213. result.hit = true;
  54214. result.pickedSprite = currentSprite;
  54215. result.distance = distance;
  54216. return result;
  54217. }
  54218. return null;
  54219. };
  54220. SpriteManager.prototype.render = function () {
  54221. // Check
  54222. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54223. return;
  54224. var engine = this._scene.getEngine();
  54225. var baseSize = this._spriteTexture.getBaseSize();
  54226. // Sprites
  54227. var deltaTime = engine.getDeltaTime();
  54228. var max = Math.min(this._capacity, this.sprites.length);
  54229. var rowSize = baseSize.width / this.cellWidth;
  54230. var offset = 0;
  54231. for (var index = 0; index < max; index++) {
  54232. var sprite = this.sprites[index];
  54233. if (!sprite || !sprite.isVisible) {
  54234. continue;
  54235. }
  54236. sprite._animate(deltaTime);
  54237. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54238. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54239. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54240. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54241. }
  54242. this._buffer.update(this._vertexData);
  54243. // Render
  54244. var effect = this._effectBase;
  54245. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54246. effect = this._effectFog;
  54247. }
  54248. engine.enableEffect(effect);
  54249. var viewMatrix = this._scene.getViewMatrix();
  54250. effect.setTexture("diffuseSampler", this._spriteTexture);
  54251. effect.setMatrix("view", viewMatrix);
  54252. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54253. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54254. // Fog
  54255. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54256. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54257. effect.setColor3("vFogColor", this._scene.fogColor);
  54258. }
  54259. // VBOs
  54260. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54261. // Draw order
  54262. engine.setDepthFunctionToLessOrEqual();
  54263. effect.setBool("alphaTest", true);
  54264. engine.setColorWrite(false);
  54265. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  54266. engine.setColorWrite(true);
  54267. effect.setBool("alphaTest", false);
  54268. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54269. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  54270. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54271. };
  54272. SpriteManager.prototype.dispose = function () {
  54273. if (this._buffer) {
  54274. this._buffer.dispose();
  54275. this._buffer = null;
  54276. }
  54277. if (this._indexBuffer) {
  54278. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54279. this._indexBuffer = null;
  54280. }
  54281. if (this._spriteTexture) {
  54282. this._spriteTexture.dispose();
  54283. this._spriteTexture = null;
  54284. }
  54285. // Remove from scene
  54286. var index = this._scene.spriteManagers.indexOf(this);
  54287. this._scene.spriteManagers.splice(index, 1);
  54288. // Callback
  54289. this.onDisposeObservable.notifyObservers(this);
  54290. this.onDisposeObservable.clear();
  54291. };
  54292. return SpriteManager;
  54293. }());
  54294. BABYLON.SpriteManager = SpriteManager;
  54295. })(BABYLON || (BABYLON = {}));
  54296. //# sourceMappingURL=babylon.spriteManager.js.map
  54297. var BABYLON;
  54298. (function (BABYLON) {
  54299. var Sprite = /** @class */ (function () {
  54300. function Sprite(name, manager) {
  54301. this.name = name;
  54302. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54303. this.width = 1.0;
  54304. this.height = 1.0;
  54305. this.angle = 0;
  54306. this.cellIndex = 0;
  54307. this.invertU = 0;
  54308. this.invertV = 0;
  54309. this.animations = new Array();
  54310. this.isPickable = false;
  54311. this._animationStarted = false;
  54312. this._loopAnimation = false;
  54313. this._fromIndex = 0;
  54314. this._toIndex = 0;
  54315. this._delay = 0;
  54316. this._direction = 1;
  54317. this._time = 0;
  54318. /**
  54319. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  54320. */
  54321. this.isVisible = true;
  54322. this._manager = manager;
  54323. this._manager.sprites.push(this);
  54324. this.position = BABYLON.Vector3.Zero();
  54325. }
  54326. Object.defineProperty(Sprite.prototype, "size", {
  54327. get: function () {
  54328. return this.width;
  54329. },
  54330. set: function (value) {
  54331. this.width = value;
  54332. this.height = value;
  54333. },
  54334. enumerable: true,
  54335. configurable: true
  54336. });
  54337. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54338. this._fromIndex = from;
  54339. this._toIndex = to;
  54340. this._loopAnimation = loop;
  54341. this._delay = delay;
  54342. this._animationStarted = true;
  54343. this._direction = from < to ? 1 : -1;
  54344. this.cellIndex = from;
  54345. this._time = 0;
  54346. this._onAnimationEnd = onAnimationEnd;
  54347. };
  54348. Sprite.prototype.stopAnimation = function () {
  54349. this._animationStarted = false;
  54350. };
  54351. /** @hidden */
  54352. Sprite.prototype._animate = function (deltaTime) {
  54353. if (!this._animationStarted)
  54354. return;
  54355. this._time += deltaTime;
  54356. if (this._time > this._delay) {
  54357. this._time = this._time % this._delay;
  54358. this.cellIndex += this._direction;
  54359. if (this.cellIndex > this._toIndex) {
  54360. if (this._loopAnimation) {
  54361. this.cellIndex = this._fromIndex;
  54362. }
  54363. else {
  54364. this.cellIndex = this._toIndex;
  54365. this._animationStarted = false;
  54366. if (this._onAnimationEnd) {
  54367. this._onAnimationEnd();
  54368. }
  54369. if (this.disposeWhenFinishedAnimating) {
  54370. this.dispose();
  54371. }
  54372. }
  54373. }
  54374. }
  54375. };
  54376. Sprite.prototype.dispose = function () {
  54377. for (var i = 0; i < this._manager.sprites.length; i++) {
  54378. if (this._manager.sprites[i] == this) {
  54379. this._manager.sprites.splice(i, 1);
  54380. }
  54381. }
  54382. };
  54383. return Sprite;
  54384. }());
  54385. BABYLON.Sprite = Sprite;
  54386. })(BABYLON || (BABYLON = {}));
  54387. //# sourceMappingURL=babylon.sprite.js.map
  54388. var BABYLON;
  54389. (function (BABYLON) {
  54390. var IntersectionInfo = /** @class */ (function () {
  54391. function IntersectionInfo(bu, bv, distance) {
  54392. this.bu = bu;
  54393. this.bv = bv;
  54394. this.distance = distance;
  54395. this.faceId = 0;
  54396. this.subMeshId = 0;
  54397. }
  54398. return IntersectionInfo;
  54399. }());
  54400. BABYLON.IntersectionInfo = IntersectionInfo;
  54401. /**
  54402. * Information about the result of picking within a scene
  54403. * See https://doc.babylonjs.com/babylon101/picking_collisions
  54404. */
  54405. var PickingInfo = /** @class */ (function () {
  54406. function PickingInfo() {
  54407. /**
  54408. * If the pick collided with an object
  54409. */
  54410. this.hit = false;
  54411. /**
  54412. * Distance away where the pick collided
  54413. */
  54414. this.distance = 0;
  54415. /**
  54416. * The location of pick collision
  54417. */
  54418. this.pickedPoint = null;
  54419. /**
  54420. * The mesh corresponding the the pick collision
  54421. */
  54422. this.pickedMesh = null;
  54423. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  54424. this.bu = 0;
  54425. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  54426. this.bv = 0;
  54427. /** The id of the face on the mesh that was picked */
  54428. this.faceId = -1;
  54429. /** Id of the the submesh that was picked */
  54430. this.subMeshId = 0;
  54431. /** If a sprite was picked, this will be the sprite the pick collided with */
  54432. this.pickedSprite = null;
  54433. /**
  54434. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  54435. */
  54436. this.originMesh = null;
  54437. /**
  54438. * The ray that was used to perform the picking.
  54439. */
  54440. this.ray = null;
  54441. }
  54442. /**
  54443. * Gets the normal correspodning to the face the pick collided with
  54444. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  54445. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  54446. * @returns The normal correspodning to the face the pick collided with
  54447. */
  54448. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54449. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54450. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54451. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54452. return null;
  54453. }
  54454. var indices = this.pickedMesh.getIndices();
  54455. if (!indices) {
  54456. return null;
  54457. }
  54458. var result;
  54459. if (useVerticesNormals) {
  54460. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54461. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54462. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54463. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54464. normal0 = normal0.scale(this.bu);
  54465. normal1 = normal1.scale(this.bv);
  54466. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54467. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54468. }
  54469. else {
  54470. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54471. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54472. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54473. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54474. var p1p2 = vertex1.subtract(vertex2);
  54475. var p3p2 = vertex3.subtract(vertex2);
  54476. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54477. }
  54478. if (useWorldCoordinates) {
  54479. var wm = this.pickedMesh.getWorldMatrix();
  54480. if (this.pickedMesh.nonUniformScaling) {
  54481. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  54482. wm = BABYLON.Tmp.Matrix[0];
  54483. wm.setTranslationFromFloats(0, 0, 0);
  54484. wm.invert();
  54485. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  54486. wm = BABYLON.Tmp.Matrix[1];
  54487. }
  54488. result = BABYLON.Vector3.TransformNormal(result, wm);
  54489. }
  54490. result.normalize();
  54491. return result;
  54492. };
  54493. /**
  54494. * Gets the texture coordinates of where the pick occured
  54495. * @returns the vector containing the coordnates of the texture
  54496. */
  54497. PickingInfo.prototype.getTextureCoordinates = function () {
  54498. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54499. return null;
  54500. }
  54501. var indices = this.pickedMesh.getIndices();
  54502. if (!indices) {
  54503. return null;
  54504. }
  54505. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54506. if (!uvs) {
  54507. return null;
  54508. }
  54509. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54510. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54511. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54512. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54513. uv1 = uv1.scale(this.bu);
  54514. uv2 = uv2.scale(this.bv);
  54515. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54516. };
  54517. return PickingInfo;
  54518. }());
  54519. BABYLON.PickingInfo = PickingInfo;
  54520. })(BABYLON || (BABYLON = {}));
  54521. //# sourceMappingURL=babylon.pickingInfo.js.map
  54522. var BABYLON;
  54523. (function (BABYLON) {
  54524. var Ray = /** @class */ (function () {
  54525. function Ray(origin, direction, length) {
  54526. if (length === void 0) { length = Number.MAX_VALUE; }
  54527. this.origin = origin;
  54528. this.direction = direction;
  54529. this.length = length;
  54530. }
  54531. // Methods
  54532. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54533. var d = 0.0;
  54534. var maxValue = Number.MAX_VALUE;
  54535. var inv;
  54536. var min;
  54537. var max;
  54538. var temp;
  54539. if (Math.abs(this.direction.x) < 0.0000001) {
  54540. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54541. return false;
  54542. }
  54543. }
  54544. else {
  54545. inv = 1.0 / this.direction.x;
  54546. min = (minimum.x - this.origin.x) * inv;
  54547. max = (maximum.x - this.origin.x) * inv;
  54548. if (max === -Infinity) {
  54549. max = Infinity;
  54550. }
  54551. if (min > max) {
  54552. temp = min;
  54553. min = max;
  54554. max = temp;
  54555. }
  54556. d = Math.max(min, d);
  54557. maxValue = Math.min(max, maxValue);
  54558. if (d > maxValue) {
  54559. return false;
  54560. }
  54561. }
  54562. if (Math.abs(this.direction.y) < 0.0000001) {
  54563. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54564. return false;
  54565. }
  54566. }
  54567. else {
  54568. inv = 1.0 / this.direction.y;
  54569. min = (minimum.y - this.origin.y) * inv;
  54570. max = (maximum.y - this.origin.y) * inv;
  54571. if (max === -Infinity) {
  54572. max = Infinity;
  54573. }
  54574. if (min > max) {
  54575. temp = min;
  54576. min = max;
  54577. max = temp;
  54578. }
  54579. d = Math.max(min, d);
  54580. maxValue = Math.min(max, maxValue);
  54581. if (d > maxValue) {
  54582. return false;
  54583. }
  54584. }
  54585. if (Math.abs(this.direction.z) < 0.0000001) {
  54586. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54587. return false;
  54588. }
  54589. }
  54590. else {
  54591. inv = 1.0 / this.direction.z;
  54592. min = (minimum.z - this.origin.z) * inv;
  54593. max = (maximum.z - this.origin.z) * inv;
  54594. if (max === -Infinity) {
  54595. max = Infinity;
  54596. }
  54597. if (min > max) {
  54598. temp = min;
  54599. min = max;
  54600. max = temp;
  54601. }
  54602. d = Math.max(min, d);
  54603. maxValue = Math.min(max, maxValue);
  54604. if (d > maxValue) {
  54605. return false;
  54606. }
  54607. }
  54608. return true;
  54609. };
  54610. Ray.prototype.intersectsBox = function (box) {
  54611. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54612. };
  54613. Ray.prototype.intersectsSphere = function (sphere) {
  54614. var x = sphere.center.x - this.origin.x;
  54615. var y = sphere.center.y - this.origin.y;
  54616. var z = sphere.center.z - this.origin.z;
  54617. var pyth = (x * x) + (y * y) + (z * z);
  54618. var rr = sphere.radius * sphere.radius;
  54619. if (pyth <= rr) {
  54620. return true;
  54621. }
  54622. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54623. if (dot < 0.0) {
  54624. return false;
  54625. }
  54626. var temp = pyth - (dot * dot);
  54627. return temp <= rr;
  54628. };
  54629. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54630. if (!this._edge1) {
  54631. this._edge1 = BABYLON.Vector3.Zero();
  54632. this._edge2 = BABYLON.Vector3.Zero();
  54633. this._pvec = BABYLON.Vector3.Zero();
  54634. this._tvec = BABYLON.Vector3.Zero();
  54635. this._qvec = BABYLON.Vector3.Zero();
  54636. }
  54637. vertex1.subtractToRef(vertex0, this._edge1);
  54638. vertex2.subtractToRef(vertex0, this._edge2);
  54639. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54640. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54641. if (det === 0) {
  54642. return null;
  54643. }
  54644. var invdet = 1 / det;
  54645. this.origin.subtractToRef(vertex0, this._tvec);
  54646. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54647. if (bu < 0 || bu > 1.0) {
  54648. return null;
  54649. }
  54650. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54651. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54652. if (bv < 0 || bu + bv > 1.0) {
  54653. return null;
  54654. }
  54655. //check if the distance is longer than the predefined length.
  54656. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54657. if (distance > this.length) {
  54658. return null;
  54659. }
  54660. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54661. };
  54662. Ray.prototype.intersectsPlane = function (plane) {
  54663. var distance;
  54664. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54665. if (Math.abs(result1) < 9.99999997475243E-07) {
  54666. return null;
  54667. }
  54668. else {
  54669. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54670. distance = (-plane.d - result2) / result1;
  54671. if (distance < 0.0) {
  54672. if (distance < -9.99999997475243E-07) {
  54673. return null;
  54674. }
  54675. else {
  54676. return 0;
  54677. }
  54678. }
  54679. return distance;
  54680. }
  54681. };
  54682. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54683. var tm = BABYLON.Tmp.Matrix[0];
  54684. mesh.getWorldMatrix().invertToRef(tm);
  54685. if (this._tmpRay) {
  54686. Ray.TransformToRef(this, tm, this._tmpRay);
  54687. }
  54688. else {
  54689. this._tmpRay = Ray.Transform(this, tm);
  54690. }
  54691. return mesh.intersects(this._tmpRay, fastCheck);
  54692. };
  54693. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54694. if (results) {
  54695. results.length = 0;
  54696. }
  54697. else {
  54698. results = [];
  54699. }
  54700. for (var i = 0; i < meshes.length; i++) {
  54701. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54702. if (pickInfo.hit) {
  54703. results.push(pickInfo);
  54704. }
  54705. }
  54706. results.sort(this._comparePickingInfo);
  54707. return results;
  54708. };
  54709. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54710. if (pickingInfoA.distance < pickingInfoB.distance) {
  54711. return -1;
  54712. }
  54713. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54714. return 1;
  54715. }
  54716. else {
  54717. return 0;
  54718. }
  54719. };
  54720. /**
  54721. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54722. * @param sega the first point of the segment to test the intersection against
  54723. * @param segb the second point of the segment to test the intersection against
  54724. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54725. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54726. */
  54727. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54728. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54729. var u = segb.subtract(sega);
  54730. var v = rsegb.subtract(this.origin);
  54731. var w = sega.subtract(this.origin);
  54732. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54733. var b = BABYLON.Vector3.Dot(u, v);
  54734. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54735. var d = BABYLON.Vector3.Dot(u, w);
  54736. var e = BABYLON.Vector3.Dot(v, w);
  54737. var D = a * c - b * b; // always >= 0
  54738. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54739. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54740. // compute the line parameters of the two closest points
  54741. if (D < Ray.smallnum) { // the lines are almost parallel
  54742. sN = 0.0; // force using point P0 on segment S1
  54743. sD = 1.0; // to prevent possible division by 0.0 later
  54744. tN = e;
  54745. tD = c;
  54746. }
  54747. else { // get the closest points on the infinite lines
  54748. sN = (b * e - c * d);
  54749. tN = (a * e - b * d);
  54750. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54751. sN = 0.0;
  54752. tN = e;
  54753. tD = c;
  54754. }
  54755. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54756. sN = sD;
  54757. tN = e + b;
  54758. tD = c;
  54759. }
  54760. }
  54761. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54762. tN = 0.0;
  54763. // recompute sc for this edge
  54764. if (-d < 0.0) {
  54765. sN = 0.0;
  54766. }
  54767. else if (-d > a)
  54768. sN = sD;
  54769. else {
  54770. sN = -d;
  54771. sD = a;
  54772. }
  54773. }
  54774. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54775. tN = tD;
  54776. // recompute sc for this edge
  54777. if ((-d + b) < 0.0) {
  54778. sN = 0;
  54779. }
  54780. else if ((-d + b) > a) {
  54781. sN = sD;
  54782. }
  54783. else {
  54784. sN = (-d + b);
  54785. sD = a;
  54786. }
  54787. }
  54788. // finally do the division to get sc and tc
  54789. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54790. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54791. // get the difference of the two closest points
  54792. var qtc = v.multiplyByFloats(tc, tc, tc);
  54793. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54794. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54795. if (isIntersected) {
  54796. return qtc.length();
  54797. }
  54798. return -1;
  54799. };
  54800. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54801. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54802. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54803. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54804. this.direction.normalize();
  54805. return this;
  54806. };
  54807. // Statics
  54808. Ray.Zero = function () {
  54809. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54810. };
  54811. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54812. var result = Ray.Zero();
  54813. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54814. };
  54815. /**
  54816. * 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
  54817. * transformed to the given world matrix.
  54818. * @param origin The origin point
  54819. * @param end The end point
  54820. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54821. */
  54822. Ray.CreateNewFromTo = function (origin, end, world) {
  54823. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54824. var direction = end.subtract(origin);
  54825. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54826. direction.normalize();
  54827. return Ray.Transform(new Ray(origin, direction, length), world);
  54828. };
  54829. Ray.Transform = function (ray, matrix) {
  54830. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54831. Ray.TransformToRef(ray, matrix, result);
  54832. return result;
  54833. };
  54834. Ray.TransformToRef = function (ray, matrix, result) {
  54835. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54836. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54837. result.length = ray.length;
  54838. var dir = result.direction;
  54839. var len = dir.length();
  54840. if (!(len === 0 || len === 1)) {
  54841. var num = 1.0 / len;
  54842. dir.x *= num;
  54843. dir.y *= num;
  54844. dir.z *= num;
  54845. result.length *= len;
  54846. }
  54847. };
  54848. Ray.smallnum = 0.00000001;
  54849. Ray.rayl = 10e8;
  54850. return Ray;
  54851. }());
  54852. BABYLON.Ray = Ray;
  54853. })(BABYLON || (BABYLON = {}));
  54854. //# sourceMappingURL=babylon.ray.js.map
  54855. var BABYLON;
  54856. (function (BABYLON) {
  54857. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54858. if (boxMin.x > sphereCenter.x + sphereRadius)
  54859. return false;
  54860. if (sphereCenter.x - sphereRadius > boxMax.x)
  54861. return false;
  54862. if (boxMin.y > sphereCenter.y + sphereRadius)
  54863. return false;
  54864. if (sphereCenter.y - sphereRadius > boxMax.y)
  54865. return false;
  54866. if (boxMin.z > sphereCenter.z + sphereRadius)
  54867. return false;
  54868. if (sphereCenter.z - sphereRadius > boxMax.z)
  54869. return false;
  54870. return true;
  54871. };
  54872. var getLowestRoot = (function () {
  54873. var result = { root: 0, found: false };
  54874. return function (a, b, c, maxR) {
  54875. result.root = 0;
  54876. result.found = false;
  54877. var determinant = b * b - 4.0 * a * c;
  54878. if (determinant < 0)
  54879. return result;
  54880. var sqrtD = Math.sqrt(determinant);
  54881. var r1 = (-b - sqrtD) / (2.0 * a);
  54882. var r2 = (-b + sqrtD) / (2.0 * a);
  54883. if (r1 > r2) {
  54884. var temp = r2;
  54885. r2 = r1;
  54886. r1 = temp;
  54887. }
  54888. if (r1 > 0 && r1 < maxR) {
  54889. result.root = r1;
  54890. result.found = true;
  54891. return result;
  54892. }
  54893. if (r2 > 0 && r2 < maxR) {
  54894. result.root = r2;
  54895. result.found = true;
  54896. return result;
  54897. }
  54898. return result;
  54899. };
  54900. })();
  54901. var Collider = /** @class */ (function () {
  54902. function Collider() {
  54903. this._collisionPoint = BABYLON.Vector3.Zero();
  54904. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54905. this._tempVector = BABYLON.Vector3.Zero();
  54906. this._tempVector2 = BABYLON.Vector3.Zero();
  54907. this._tempVector3 = BABYLON.Vector3.Zero();
  54908. this._tempVector4 = BABYLON.Vector3.Zero();
  54909. this._edge = BABYLON.Vector3.Zero();
  54910. this._baseToVertex = BABYLON.Vector3.Zero();
  54911. this._destinationPoint = BABYLON.Vector3.Zero();
  54912. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54913. this._displacementVector = BABYLON.Vector3.Zero();
  54914. /** @hidden */
  54915. this._radius = BABYLON.Vector3.One();
  54916. /** @hidden */
  54917. this._retry = 0;
  54918. /** @hidden */
  54919. this._basePointWorld = BABYLON.Vector3.Zero();
  54920. this._velocityWorld = BABYLON.Vector3.Zero();
  54921. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54922. this._collisionMask = -1;
  54923. }
  54924. Object.defineProperty(Collider.prototype, "collisionMask", {
  54925. get: function () {
  54926. return this._collisionMask;
  54927. },
  54928. set: function (mask) {
  54929. this._collisionMask = !isNaN(mask) ? mask : -1;
  54930. },
  54931. enumerable: true,
  54932. configurable: true
  54933. });
  54934. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54935. /**
  54936. * Gets the plane normal used to compute the sliding response (in local space)
  54937. */
  54938. get: function () {
  54939. return this._slidePlaneNormal;
  54940. },
  54941. enumerable: true,
  54942. configurable: true
  54943. });
  54944. // Methods
  54945. /** @hidden */
  54946. Collider.prototype._initialize = function (source, dir, e) {
  54947. this._velocity = dir;
  54948. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54949. this._basePoint = source;
  54950. source.multiplyToRef(this._radius, this._basePointWorld);
  54951. dir.multiplyToRef(this._radius, this._velocityWorld);
  54952. this._velocityWorldLength = this._velocityWorld.length();
  54953. this._epsilon = e;
  54954. this.collisionFound = false;
  54955. };
  54956. /** @hidden */
  54957. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54958. pa.subtractToRef(point, this._tempVector);
  54959. pb.subtractToRef(point, this._tempVector2);
  54960. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54961. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54962. if (d < 0)
  54963. return false;
  54964. pc.subtractToRef(point, this._tempVector3);
  54965. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54966. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54967. if (d < 0)
  54968. return false;
  54969. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54970. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54971. return d >= 0;
  54972. };
  54973. /** @hidden */
  54974. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54975. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54976. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54977. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54978. return false;
  54979. }
  54980. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54981. return false;
  54982. return true;
  54983. };
  54984. /** @hidden */
  54985. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54986. var t0;
  54987. var embeddedInPlane = false;
  54988. //defensive programming, actually not needed.
  54989. if (!trianglePlaneArray) {
  54990. trianglePlaneArray = [];
  54991. }
  54992. if (!trianglePlaneArray[faceIndex]) {
  54993. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54994. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54995. }
  54996. var trianglePlane = trianglePlaneArray[faceIndex];
  54997. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54998. return;
  54999. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55000. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55001. if (normalDotVelocity == 0) {
  55002. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55003. return;
  55004. embeddedInPlane = true;
  55005. t0 = 0;
  55006. }
  55007. else {
  55008. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55009. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55010. if (t0 > t1) {
  55011. var temp = t1;
  55012. t1 = t0;
  55013. t0 = temp;
  55014. }
  55015. if (t0 > 1.0 || t1 < 0.0)
  55016. return;
  55017. if (t0 < 0)
  55018. t0 = 0;
  55019. if (t0 > 1.0)
  55020. t0 = 1.0;
  55021. }
  55022. this._collisionPoint.copyFromFloats(0, 0, 0);
  55023. var found = false;
  55024. var t = 1.0;
  55025. if (!embeddedInPlane) {
  55026. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55027. this._velocity.scaleToRef(t0, this._tempVector);
  55028. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55029. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55030. found = true;
  55031. t = t0;
  55032. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55033. }
  55034. }
  55035. if (!found) {
  55036. var velocitySquaredLength = this._velocity.lengthSquared();
  55037. var a = velocitySquaredLength;
  55038. this._basePoint.subtractToRef(p1, this._tempVector);
  55039. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55040. var c = this._tempVector.lengthSquared() - 1.0;
  55041. var lowestRoot = getLowestRoot(a, b, c, t);
  55042. if (lowestRoot.found) {
  55043. t = lowestRoot.root;
  55044. found = true;
  55045. this._collisionPoint.copyFrom(p1);
  55046. }
  55047. this._basePoint.subtractToRef(p2, this._tempVector);
  55048. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55049. c = this._tempVector.lengthSquared() - 1.0;
  55050. lowestRoot = getLowestRoot(a, b, c, t);
  55051. if (lowestRoot.found) {
  55052. t = lowestRoot.root;
  55053. found = true;
  55054. this._collisionPoint.copyFrom(p2);
  55055. }
  55056. this._basePoint.subtractToRef(p3, this._tempVector);
  55057. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55058. c = this._tempVector.lengthSquared() - 1.0;
  55059. lowestRoot = getLowestRoot(a, b, c, t);
  55060. if (lowestRoot.found) {
  55061. t = lowestRoot.root;
  55062. found = true;
  55063. this._collisionPoint.copyFrom(p3);
  55064. }
  55065. p2.subtractToRef(p1, this._edge);
  55066. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55067. var edgeSquaredLength = this._edge.lengthSquared();
  55068. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55069. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55070. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55071. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55072. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55073. lowestRoot = getLowestRoot(a, b, c, t);
  55074. if (lowestRoot.found) {
  55075. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55076. if (f >= 0.0 && f <= 1.0) {
  55077. t = lowestRoot.root;
  55078. found = true;
  55079. this._edge.scaleInPlace(f);
  55080. p1.addToRef(this._edge, this._collisionPoint);
  55081. }
  55082. }
  55083. p3.subtractToRef(p2, this._edge);
  55084. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55085. edgeSquaredLength = this._edge.lengthSquared();
  55086. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55087. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55088. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55089. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55090. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55091. lowestRoot = getLowestRoot(a, b, c, t);
  55092. if (lowestRoot.found) {
  55093. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55094. if (f >= 0.0 && f <= 1.0) {
  55095. t = lowestRoot.root;
  55096. found = true;
  55097. this._edge.scaleInPlace(f);
  55098. p2.addToRef(this._edge, this._collisionPoint);
  55099. }
  55100. }
  55101. p1.subtractToRef(p3, this._edge);
  55102. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55103. edgeSquaredLength = this._edge.lengthSquared();
  55104. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55105. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55106. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55107. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55108. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55109. lowestRoot = getLowestRoot(a, b, c, t);
  55110. if (lowestRoot.found) {
  55111. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55112. if (f >= 0.0 && f <= 1.0) {
  55113. t = lowestRoot.root;
  55114. found = true;
  55115. this._edge.scaleInPlace(f);
  55116. p3.addToRef(this._edge, this._collisionPoint);
  55117. }
  55118. }
  55119. }
  55120. if (found) {
  55121. var distToCollision = t * this._velocity.length();
  55122. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55123. if (!this.intersectionPoint) {
  55124. this.intersectionPoint = this._collisionPoint.clone();
  55125. }
  55126. else {
  55127. this.intersectionPoint.copyFrom(this._collisionPoint);
  55128. }
  55129. this._nearestDistance = distToCollision;
  55130. this.collisionFound = true;
  55131. }
  55132. }
  55133. };
  55134. /** @hidden */
  55135. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55136. for (var i = indexStart; i < indexEnd; i += 3) {
  55137. var p1 = pts[indices[i] - decal];
  55138. var p2 = pts[indices[i + 1] - decal];
  55139. var p3 = pts[indices[i + 2] - decal];
  55140. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55141. }
  55142. };
  55143. /** @hidden */
  55144. Collider.prototype._getResponse = function (pos, vel) {
  55145. pos.addToRef(vel, this._destinationPoint);
  55146. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55147. this._basePoint.addToRef(vel, pos);
  55148. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55149. this._slidePlaneNormal.normalize();
  55150. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55151. pos.addInPlace(this._displacementVector);
  55152. this.intersectionPoint.addInPlace(this._displacementVector);
  55153. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55154. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55155. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55156. };
  55157. return Collider;
  55158. }());
  55159. BABYLON.Collider = Collider;
  55160. })(BABYLON || (BABYLON = {}));
  55161. //# sourceMappingURL=babylon.collider.js.map
  55162. var BABYLON;
  55163. (function (BABYLON) {
  55164. //WebWorker code will be inserted to this variable.
  55165. BABYLON.CollisionWorker = "";
  55166. /** Defines supported task for worker process */
  55167. var WorkerTaskType;
  55168. (function (WorkerTaskType) {
  55169. /** Initialization */
  55170. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55171. /** Update of geometry */
  55172. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55173. /** Evaluate collision */
  55174. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55175. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55176. /** Defines kind of replies returned by worker */
  55177. var WorkerReplyType;
  55178. (function (WorkerReplyType) {
  55179. /** Success */
  55180. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55181. /** Unkown error */
  55182. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55183. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55184. var CollisionCoordinatorWorker = /** @class */ (function () {
  55185. function CollisionCoordinatorWorker() {
  55186. var _this = this;
  55187. this._scaledPosition = BABYLON.Vector3.Zero();
  55188. this._scaledVelocity = BABYLON.Vector3.Zero();
  55189. this.onMeshUpdated = function (transformNode) {
  55190. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55191. };
  55192. this.onGeometryUpdated = function (geometry) {
  55193. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55194. };
  55195. this._afterRender = function () {
  55196. if (!_this._init)
  55197. return;
  55198. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55199. return;
  55200. }
  55201. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55202. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55203. if (_this._runningUpdated > 4) {
  55204. return;
  55205. }
  55206. ++_this._runningUpdated;
  55207. var payload = {
  55208. updatedMeshes: _this._addUpdateMeshesList,
  55209. updatedGeometries: _this._addUpdateGeometriesList,
  55210. removedGeometries: _this._toRemoveGeometryArray,
  55211. removedMeshes: _this._toRemoveMeshesArray
  55212. };
  55213. var message = {
  55214. payload: payload,
  55215. taskType: WorkerTaskType.UPDATE
  55216. };
  55217. var serializable = [];
  55218. for (var id in payload.updatedGeometries) {
  55219. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55220. //prepare transferables
  55221. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55222. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55223. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55224. }
  55225. }
  55226. _this._worker.postMessage(message, serializable);
  55227. _this._addUpdateMeshesList = {};
  55228. _this._addUpdateGeometriesList = {};
  55229. _this._toRemoveGeometryArray = [];
  55230. _this._toRemoveMeshesArray = [];
  55231. };
  55232. this._onMessageFromWorker = function (e) {
  55233. var returnData = e.data;
  55234. if (returnData.error != WorkerReplyType.SUCCESS) {
  55235. //TODO what errors can be returned from the worker?
  55236. BABYLON.Tools.Warn("error returned from worker!");
  55237. return;
  55238. }
  55239. switch (returnData.taskType) {
  55240. case WorkerTaskType.INIT:
  55241. _this._init = true;
  55242. //Update the worked with ALL of the scene's current state
  55243. _this._scene.meshes.forEach(function (mesh) {
  55244. _this.onMeshAdded(mesh);
  55245. });
  55246. _this._scene.getGeometries().forEach(function (geometry) {
  55247. _this.onGeometryAdded(geometry);
  55248. });
  55249. break;
  55250. case WorkerTaskType.UPDATE:
  55251. _this._runningUpdated--;
  55252. break;
  55253. case WorkerTaskType.COLLIDE:
  55254. var returnPayload = returnData.payload;
  55255. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55256. return;
  55257. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55258. if (callback) {
  55259. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55260. if (mesh) {
  55261. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55262. }
  55263. }
  55264. //cleanup
  55265. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55266. break;
  55267. }
  55268. };
  55269. this._collisionsCallbackArray = [];
  55270. this._init = false;
  55271. this._runningUpdated = 0;
  55272. this._addUpdateMeshesList = {};
  55273. this._addUpdateGeometriesList = {};
  55274. this._toRemoveGeometryArray = [];
  55275. this._toRemoveMeshesArray = [];
  55276. }
  55277. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55278. if (!this._init)
  55279. return;
  55280. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55281. return;
  55282. position.divideToRef(collider._radius, this._scaledPosition);
  55283. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55284. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55285. var payload = {
  55286. collider: {
  55287. position: this._scaledPosition.asArray(),
  55288. velocity: this._scaledVelocity.asArray(),
  55289. radius: collider._radius.asArray()
  55290. },
  55291. collisionId: collisionIndex,
  55292. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55293. maximumRetry: maximumRetry
  55294. };
  55295. var message = {
  55296. payload: payload,
  55297. taskType: WorkerTaskType.COLLIDE
  55298. };
  55299. this._worker.postMessage(message);
  55300. };
  55301. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55302. this._scene = scene;
  55303. this._scene.registerAfterRender(this._afterRender);
  55304. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55305. this._worker = new Worker(workerUrl);
  55306. this._worker.onmessage = this._onMessageFromWorker;
  55307. var message = {
  55308. payload: {},
  55309. taskType: WorkerTaskType.INIT
  55310. };
  55311. this._worker.postMessage(message);
  55312. };
  55313. CollisionCoordinatorWorker.prototype.destroy = function () {
  55314. this._scene.unregisterAfterRender(this._afterRender);
  55315. this._worker.terminate();
  55316. };
  55317. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55318. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55319. this.onMeshUpdated(mesh);
  55320. };
  55321. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55322. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55323. };
  55324. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55325. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55326. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55327. this.onGeometryUpdated(geometry);
  55328. };
  55329. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55330. this._toRemoveGeometryArray.push(geometry.id);
  55331. };
  55332. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55333. var submeshes = [];
  55334. if (mesh.subMeshes) {
  55335. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55336. var boundingInfo = sm.getBoundingInfo();
  55337. return {
  55338. position: idx,
  55339. verticesStart: sm.verticesStart,
  55340. verticesCount: sm.verticesCount,
  55341. indexStart: sm.indexStart,
  55342. indexCount: sm.indexCount,
  55343. hasMaterial: !!sm.getMaterial(),
  55344. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55345. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55346. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55347. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55348. };
  55349. });
  55350. }
  55351. var geometryId = null;
  55352. if (mesh instanceof BABYLON.Mesh) {
  55353. var geometry = mesh.geometry;
  55354. geometryId = geometry ? geometry.id : null;
  55355. }
  55356. else if (mesh instanceof BABYLON.InstancedMesh) {
  55357. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55358. geometryId = geometry ? geometry.id : null;
  55359. }
  55360. var boundingInfo = mesh.getBoundingInfo();
  55361. return {
  55362. uniqueId: mesh.uniqueId,
  55363. id: mesh.id,
  55364. name: mesh.name,
  55365. geometryId: geometryId,
  55366. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55367. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55368. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55369. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55370. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55371. subMeshes: submeshes,
  55372. checkCollisions: mesh.checkCollisions
  55373. };
  55374. };
  55375. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55376. return {
  55377. id: geometry.id,
  55378. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55379. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55380. indices: new Uint32Array(geometry.getIndices() || []),
  55381. };
  55382. };
  55383. return CollisionCoordinatorWorker;
  55384. }());
  55385. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55386. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55387. function CollisionCoordinatorLegacy() {
  55388. this._scaledPosition = BABYLON.Vector3.Zero();
  55389. this._scaledVelocity = BABYLON.Vector3.Zero();
  55390. this._finalPosition = BABYLON.Vector3.Zero();
  55391. }
  55392. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55393. position.divideToRef(collider._radius, this._scaledPosition);
  55394. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55395. collider.collidedMesh = null;
  55396. collider._retry = 0;
  55397. collider._initialVelocity = this._scaledVelocity;
  55398. collider._initialPosition = this._scaledPosition;
  55399. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55400. this._finalPosition.multiplyInPlace(collider._radius);
  55401. //run the callback
  55402. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55403. };
  55404. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55405. this._scene = scene;
  55406. };
  55407. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55408. //Legacy need no destruction method.
  55409. };
  55410. //No update in legacy mode
  55411. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55412. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55413. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55414. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55415. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55416. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55417. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55418. if (excludedMesh === void 0) { excludedMesh = null; }
  55419. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55420. if (collider._retry >= maximumRetry) {
  55421. finalPosition.copyFrom(position);
  55422. return;
  55423. }
  55424. // Check if this is a mesh else camera or -1
  55425. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55426. collider._initialize(position, velocity, closeDistance);
  55427. // Check all meshes
  55428. for (var index = 0; index < this._scene.meshes.length; index++) {
  55429. var mesh = this._scene.meshes[index];
  55430. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55431. mesh._checkCollision(collider);
  55432. }
  55433. }
  55434. if (!collider.collisionFound) {
  55435. position.addToRef(velocity, finalPosition);
  55436. return;
  55437. }
  55438. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55439. collider._getResponse(position, velocity);
  55440. }
  55441. if (velocity.length() <= closeDistance) {
  55442. finalPosition.copyFrom(position);
  55443. return;
  55444. }
  55445. collider._retry++;
  55446. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55447. };
  55448. return CollisionCoordinatorLegacy;
  55449. }());
  55450. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55451. })(BABYLON || (BABYLON = {}));
  55452. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55453. var BABYLON;
  55454. (function (BABYLON) {
  55455. /**
  55456. * A particle represents one of the element emitted by a particle system.
  55457. * This is mainly define by its coordinates, direction, velocity and age.
  55458. */
  55459. var Particle = /** @class */ (function () {
  55460. /**
  55461. * Creates a new instance Particle
  55462. * @param particleSystem the particle system the particle belongs to
  55463. */
  55464. function Particle(
  55465. /**
  55466. * particleSystem the particle system the particle belongs to.
  55467. */
  55468. particleSystem) {
  55469. this.particleSystem = particleSystem;
  55470. /**
  55471. * The world position of the particle in the scene.
  55472. */
  55473. this.position = BABYLON.Vector3.Zero();
  55474. /**
  55475. * The world direction of the particle in the scene.
  55476. */
  55477. this.direction = BABYLON.Vector3.Zero();
  55478. /**
  55479. * The color of the particle.
  55480. */
  55481. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55482. /**
  55483. * The color change of the particle per step.
  55484. */
  55485. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55486. /**
  55487. * Defines how long will the life of the particle be.
  55488. */
  55489. this.lifeTime = 1.0;
  55490. /**
  55491. * The current age of the particle.
  55492. */
  55493. this.age = 0;
  55494. /**
  55495. * The current size of the particle.
  55496. */
  55497. this.size = 0;
  55498. /**
  55499. * The current scale of the particle.
  55500. */
  55501. this.scale = new BABYLON.Vector2(1, 1);
  55502. /**
  55503. * The current angle of the particle.
  55504. */
  55505. this.angle = 0;
  55506. /**
  55507. * Defines how fast is the angle changing.
  55508. */
  55509. this.angularSpeed = 0;
  55510. /**
  55511. * Defines the cell index used by the particle to be rendered from a sprite.
  55512. */
  55513. this.cellIndex = 0;
  55514. /** @hidden */
  55515. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  55516. /** @hidden */
  55517. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  55518. /** @hidden */
  55519. this._currentSize1 = 0;
  55520. /** @hidden */
  55521. this._currentSize2 = 0;
  55522. /** @hidden */
  55523. this._currentAngularSpeed1 = 0;
  55524. /** @hidden */
  55525. this._currentAngularSpeed2 = 0;
  55526. /** @hidden */
  55527. this._currentVelocity1 = 0;
  55528. /** @hidden */
  55529. this._currentVelocity2 = 0;
  55530. /** @hidden */
  55531. this._currentLimitVelocity1 = 0;
  55532. /** @hidden */
  55533. this._currentLimitVelocity2 = 0;
  55534. /** @hidden */
  55535. this._currentDrag1 = 0;
  55536. /** @hidden */
  55537. this._currentDrag2 = 0;
  55538. if (!this.particleSystem.isAnimationSheetEnabled) {
  55539. return;
  55540. }
  55541. this.updateCellInfoFromSystem();
  55542. }
  55543. Particle.prototype.updateCellInfoFromSystem = function () {
  55544. this.cellIndex = this.particleSystem.startSpriteCellID;
  55545. };
  55546. /**
  55547. * Defines how the sprite cell index is updated for the particle
  55548. */
  55549. Particle.prototype.updateCellIndex = function () {
  55550. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  55551. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  55552. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  55553. };
  55554. /**
  55555. * Copy the properties of particle to another one.
  55556. * @param other the particle to copy the information to.
  55557. */
  55558. Particle.prototype.copyTo = function (other) {
  55559. other.position.copyFrom(this.position);
  55560. if (this._initialDirection) {
  55561. if (other._initialDirection) {
  55562. other._initialDirection.copyFrom(this._initialDirection);
  55563. }
  55564. else {
  55565. other._initialDirection = this._initialDirection.clone();
  55566. }
  55567. }
  55568. else {
  55569. other._initialDirection = null;
  55570. }
  55571. other.direction.copyFrom(this.direction);
  55572. other.color.copyFrom(this.color);
  55573. other.colorStep.copyFrom(this.colorStep);
  55574. other.lifeTime = this.lifeTime;
  55575. other.age = this.age;
  55576. other.size = this.size;
  55577. other.scale.copyFrom(this.scale);
  55578. other.angle = this.angle;
  55579. other.angularSpeed = this.angularSpeed;
  55580. other.particleSystem = this.particleSystem;
  55581. other.cellIndex = this.cellIndex;
  55582. if (this._currentColorGradient) {
  55583. other._currentColorGradient = this._currentColorGradient;
  55584. other._currentColor1.copyFrom(this._currentColor1);
  55585. other._currentColor2.copyFrom(this._currentColor2);
  55586. }
  55587. if (this._currentSizeGradient) {
  55588. other._currentSizeGradient = this._currentSizeGradient;
  55589. other._currentSize1 = this._currentSize1;
  55590. other._currentSize2 = this._currentSize2;
  55591. }
  55592. if (this._currentAngularSpeedGradient) {
  55593. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  55594. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  55595. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  55596. }
  55597. if (this._currentVelocityGradient) {
  55598. other._currentVelocityGradient = this._currentVelocityGradient;
  55599. other._currentVelocity1 = this._currentVelocity1;
  55600. other._currentVelocity2 = this._currentVelocity2;
  55601. }
  55602. if (this._currentLimitVelocityGradient) {
  55603. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  55604. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  55605. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  55606. }
  55607. if (this._currentDragGradient) {
  55608. other._currentDragGradient = this._currentDragGradient;
  55609. other._currentDrag1 = this._currentDrag1;
  55610. other._currentDrag2 = this._currentDrag2;
  55611. }
  55612. if (this.particleSystem.isAnimationSheetEnabled) {
  55613. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  55614. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  55615. }
  55616. };
  55617. return Particle;
  55618. }());
  55619. BABYLON.Particle = Particle;
  55620. })(BABYLON || (BABYLON = {}));
  55621. //# sourceMappingURL=babylon.particle.js.map
  55622. var BABYLON;
  55623. (function (BABYLON) {
  55624. /**
  55625. * This represents the base class for particle system in Babylon.
  55626. * 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.
  55627. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55628. * @example https://doc.babylonjs.com/babylon101/particles
  55629. */
  55630. var BaseParticleSystem = /** @class */ (function () {
  55631. /**
  55632. * Instantiates a particle system.
  55633. * 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.
  55634. * @param name The name of the particle system
  55635. */
  55636. function BaseParticleSystem(name) {
  55637. /**
  55638. * List of animations used by the particle system.
  55639. */
  55640. this.animations = [];
  55641. /**
  55642. * The rendering group used by the Particle system to chose when to render.
  55643. */
  55644. this.renderingGroupId = 0;
  55645. /**
  55646. * The emitter represents the Mesh or position we are attaching the particle system to.
  55647. */
  55648. this.emitter = null;
  55649. /**
  55650. * The maximum number of particles to emit per frame
  55651. */
  55652. this.emitRate = 10;
  55653. /**
  55654. * If you want to launch only a few particles at once, that can be done, as well.
  55655. */
  55656. this.manualEmitCount = -1;
  55657. /**
  55658. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55659. */
  55660. this.updateSpeed = 0.01;
  55661. /**
  55662. * The amount of time the particle system is running (depends of the overall update speed).
  55663. */
  55664. this.targetStopDuration = 0;
  55665. /**
  55666. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55667. */
  55668. this.disposeOnStop = false;
  55669. /**
  55670. * Minimum power of emitting particles.
  55671. */
  55672. this.minEmitPower = 1;
  55673. /**
  55674. * Maximum power of emitting particles.
  55675. */
  55676. this.maxEmitPower = 1;
  55677. /**
  55678. * Minimum life time of emitting particles.
  55679. */
  55680. this.minLifeTime = 1;
  55681. /**
  55682. * Maximum life time of emitting particles.
  55683. */
  55684. this.maxLifeTime = 1;
  55685. /**
  55686. * Minimum Size of emitting particles.
  55687. */
  55688. this.minSize = 1;
  55689. /**
  55690. * Maximum Size of emitting particles.
  55691. */
  55692. this.maxSize = 1;
  55693. /**
  55694. * Minimum scale of emitting particles on X axis.
  55695. */
  55696. this.minScaleX = 1;
  55697. /**
  55698. * Maximum scale of emitting particles on X axis.
  55699. */
  55700. this.maxScaleX = 1;
  55701. /**
  55702. * Minimum scale of emitting particles on Y axis.
  55703. */
  55704. this.minScaleY = 1;
  55705. /**
  55706. * Maximum scale of emitting particles on Y axis.
  55707. */
  55708. this.maxScaleY = 1;
  55709. /**
  55710. * Gets or sets the minimal initial rotation in radians.
  55711. */
  55712. this.minInitialRotation = 0;
  55713. /**
  55714. * Gets or sets the maximal initial rotation in radians.
  55715. */
  55716. this.maxInitialRotation = 0;
  55717. /**
  55718. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55719. */
  55720. this.minAngularSpeed = 0;
  55721. /**
  55722. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55723. */
  55724. this.maxAngularSpeed = 0;
  55725. /**
  55726. * The layer mask we are rendering the particles through.
  55727. */
  55728. this.layerMask = 0x0FFFFFFF;
  55729. /**
  55730. * This can help using your own shader to render the particle system.
  55731. * The according effect will be created
  55732. */
  55733. this.customShader = null;
  55734. /**
  55735. * By default particle system starts as soon as they are created. This prevents the
  55736. * automatic start to happen and let you decide when to start emitting particles.
  55737. */
  55738. this.preventAutoStart = false;
  55739. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  55740. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  55741. /**
  55742. * Callback triggered when the particle animation is ending.
  55743. */
  55744. this.onAnimationEnd = null;
  55745. /**
  55746. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55747. */
  55748. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55749. /**
  55750. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55751. * to override the particles.
  55752. */
  55753. this.forceDepthWrite = false;
  55754. /** 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 */
  55755. this.preWarmCycles = 0;
  55756. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55757. this.preWarmStepOffset = 1;
  55758. /**
  55759. * 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)
  55760. */
  55761. this.spriteCellChangeSpeed = 1;
  55762. /**
  55763. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55764. */
  55765. this.startSpriteCellID = 0;
  55766. /**
  55767. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55768. */
  55769. this.endSpriteCellID = 0;
  55770. /**
  55771. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55772. */
  55773. this.spriteCellWidth = 0;
  55774. /**
  55775. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55776. */
  55777. this.spriteCellHeight = 0;
  55778. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55779. this.translationPivot = new BABYLON.Vector2(0, 0);
  55780. /**
  55781. * You can use gravity if you want to give an orientation to your particles.
  55782. */
  55783. this.gravity = BABYLON.Vector3.Zero();
  55784. this._colorGradients = null;
  55785. this._sizeGradients = null;
  55786. this._lifeTimeGradients = null;
  55787. this._angularSpeedGradients = null;
  55788. this._velocityGradients = null;
  55789. this._limitVelocityGradients = null;
  55790. this._dragGradients = null;
  55791. this._emitRateGradients = null;
  55792. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  55793. this.limitVelocityDamping = 0.4;
  55794. /**
  55795. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55796. */
  55797. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55798. /**
  55799. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55800. */
  55801. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55802. /**
  55803. * Color the particle will have at the end of its lifetime
  55804. */
  55805. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55806. /**
  55807. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55808. */
  55809. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55810. /**
  55811. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55812. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55813. */
  55814. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55815. this._isBillboardBased = true;
  55816. /**
  55817. * Local cache of defines for image processing.
  55818. */
  55819. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  55820. this.id = name;
  55821. this.name = name;
  55822. }
  55823. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  55824. /**
  55825. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  55826. */
  55827. get: function () {
  55828. return this._isAnimationSheetEnabled;
  55829. },
  55830. set: function (value) {
  55831. if (this._isAnimationSheetEnabled == value) {
  55832. return;
  55833. }
  55834. this._isAnimationSheetEnabled = value;
  55835. this._reset();
  55836. },
  55837. enumerable: true,
  55838. configurable: true
  55839. });
  55840. /**
  55841. * Gets the current list of drag gradients.
  55842. * You must use addDragGradient and removeDragGradient to udpate this list
  55843. * @returns the list of drag gradients
  55844. */
  55845. BaseParticleSystem.prototype.getDragGradients = function () {
  55846. return this._dragGradients;
  55847. };
  55848. /**
  55849. * Gets the current list of limit velocity gradients.
  55850. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  55851. * @returns the list of limit velocity gradients
  55852. */
  55853. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  55854. return this._limitVelocityGradients;
  55855. };
  55856. /**
  55857. * Gets the current list of color gradients.
  55858. * You must use addColorGradient and removeColorGradient to udpate this list
  55859. * @returns the list of color gradients
  55860. */
  55861. BaseParticleSystem.prototype.getColorGradients = function () {
  55862. return this._colorGradients;
  55863. };
  55864. /**
  55865. * Gets the current list of size gradients.
  55866. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55867. * @returns the list of size gradients
  55868. */
  55869. BaseParticleSystem.prototype.getSizeGradients = function () {
  55870. return this._sizeGradients;
  55871. };
  55872. /**
  55873. * Gets the current list of life time gradients.
  55874. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55875. * @returns the list of life time gradients
  55876. */
  55877. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  55878. return this._lifeTimeGradients;
  55879. };
  55880. /**
  55881. * Gets the current list of angular speed gradients.
  55882. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55883. * @returns the list of angular speed gradients
  55884. */
  55885. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  55886. return this._angularSpeedGradients;
  55887. };
  55888. /**
  55889. * Gets the current list of velocity gradients.
  55890. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55891. * @returns the list of velocity gradients
  55892. */
  55893. BaseParticleSystem.prototype.getVelocityGradients = function () {
  55894. return this._velocityGradients;
  55895. };
  55896. /**
  55897. * Gets the current list of emit rate gradients.
  55898. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  55899. * @returns the list of emit rate gradients
  55900. */
  55901. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  55902. return this._emitRateGradients;
  55903. };
  55904. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  55905. /**
  55906. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55907. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55908. */
  55909. get: function () {
  55910. if (this.particleEmitterType.direction1) {
  55911. return this.particleEmitterType.direction1;
  55912. }
  55913. return BABYLON.Vector3.Zero();
  55914. },
  55915. set: function (value) {
  55916. if (this.particleEmitterType.direction1) {
  55917. this.particleEmitterType.direction1 = value;
  55918. }
  55919. },
  55920. enumerable: true,
  55921. configurable: true
  55922. });
  55923. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  55924. /**
  55925. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55926. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55927. */
  55928. get: function () {
  55929. if (this.particleEmitterType.direction2) {
  55930. return this.particleEmitterType.direction2;
  55931. }
  55932. return BABYLON.Vector3.Zero();
  55933. },
  55934. set: function (value) {
  55935. if (this.particleEmitterType.direction2) {
  55936. this.particleEmitterType.direction2 = value;
  55937. }
  55938. },
  55939. enumerable: true,
  55940. configurable: true
  55941. });
  55942. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  55943. /**
  55944. * 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.
  55945. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55946. */
  55947. get: function () {
  55948. if (this.particleEmitterType.minEmitBox) {
  55949. return this.particleEmitterType.minEmitBox;
  55950. }
  55951. return BABYLON.Vector3.Zero();
  55952. },
  55953. set: function (value) {
  55954. if (this.particleEmitterType.minEmitBox) {
  55955. this.particleEmitterType.minEmitBox = value;
  55956. }
  55957. },
  55958. enumerable: true,
  55959. configurable: true
  55960. });
  55961. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  55962. /**
  55963. * 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.
  55964. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55965. */
  55966. get: function () {
  55967. if (this.particleEmitterType.maxEmitBox) {
  55968. return this.particleEmitterType.maxEmitBox;
  55969. }
  55970. return BABYLON.Vector3.Zero();
  55971. },
  55972. set: function (value) {
  55973. if (this.particleEmitterType.maxEmitBox) {
  55974. this.particleEmitterType.maxEmitBox = value;
  55975. }
  55976. },
  55977. enumerable: true,
  55978. configurable: true
  55979. });
  55980. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  55981. /**
  55982. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55983. */
  55984. get: function () {
  55985. return this._isBillboardBased;
  55986. },
  55987. set: function (value) {
  55988. if (this._isBillboardBased === value) {
  55989. return;
  55990. }
  55991. this._isBillboardBased = value;
  55992. this._reset();
  55993. },
  55994. enumerable: true,
  55995. configurable: true
  55996. });
  55997. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  55998. /**
  55999. * Gets the image processing configuration used either in this material.
  56000. */
  56001. get: function () {
  56002. return this._imageProcessingConfiguration;
  56003. },
  56004. /**
  56005. * Sets the Default image processing configuration used either in the this material.
  56006. *
  56007. * If sets to null, the scene one is in use.
  56008. */
  56009. set: function (value) {
  56010. this._attachImageProcessingConfiguration(value);
  56011. },
  56012. enumerable: true,
  56013. configurable: true
  56014. });
  56015. /**
  56016. * Attaches a new image processing configuration to the Standard Material.
  56017. * @param configuration
  56018. */
  56019. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  56020. if (configuration === this._imageProcessingConfiguration) {
  56021. return;
  56022. }
  56023. // Pick the scene configuration if needed.
  56024. if (!configuration) {
  56025. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  56026. }
  56027. else {
  56028. this._imageProcessingConfiguration = configuration;
  56029. }
  56030. };
  56031. /** @hidden */
  56032. BaseParticleSystem.prototype._reset = function () {
  56033. };
  56034. /**
  56035. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  56036. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56037. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56038. * @returns the emitter
  56039. */
  56040. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  56041. var particleEmitter = new BABYLON.PointParticleEmitter();
  56042. particleEmitter.direction1 = direction1;
  56043. particleEmitter.direction2 = direction2;
  56044. this.particleEmitterType = particleEmitter;
  56045. return particleEmitter;
  56046. };
  56047. /**
  56048. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  56049. * @param radius The radius of the hemisphere to emit from
  56050. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56051. * @returns the emitter
  56052. */
  56053. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  56054. if (radius === void 0) { radius = 1; }
  56055. if (radiusRange === void 0) { radiusRange = 1; }
  56056. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  56057. this.particleEmitterType = particleEmitter;
  56058. return particleEmitter;
  56059. };
  56060. /**
  56061. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  56062. * @param radius The radius of the sphere to emit from
  56063. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56064. * @returns the emitter
  56065. */
  56066. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  56067. if (radius === void 0) { radius = 1; }
  56068. if (radiusRange === void 0) { radiusRange = 1; }
  56069. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  56070. this.particleEmitterType = particleEmitter;
  56071. return particleEmitter;
  56072. };
  56073. /**
  56074. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  56075. * @param radius The radius of the sphere to emit from
  56076. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56077. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56078. * @returns the emitter
  56079. */
  56080. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56081. if (radius === void 0) { radius = 1; }
  56082. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56083. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56084. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56085. this.particleEmitterType = particleEmitter;
  56086. return particleEmitter;
  56087. };
  56088. /**
  56089. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  56090. * @param radius The radius of the emission cylinder
  56091. * @param height The height of the emission cylinder
  56092. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  56093. * @param directionRandomizer How much to randomize the particle direction [0-1]
  56094. * @returns the emitter
  56095. */
  56096. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  56097. if (radius === void 0) { radius = 1; }
  56098. if (height === void 0) { height = 1; }
  56099. if (radiusRange === void 0) { radiusRange = 1; }
  56100. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56101. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  56102. this.particleEmitterType = particleEmitter;
  56103. return particleEmitter;
  56104. };
  56105. /**
  56106. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  56107. * @param radius The radius of the cone to emit from
  56108. * @param angle The base angle of the cone
  56109. * @returns the emitter
  56110. */
  56111. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56112. if (radius === void 0) { radius = 1; }
  56113. if (angle === void 0) { angle = Math.PI / 4; }
  56114. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56115. this.particleEmitterType = particleEmitter;
  56116. return particleEmitter;
  56117. };
  56118. /**
  56119. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56120. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56121. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56122. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56123. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56124. * @returns the emitter
  56125. */
  56126. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56127. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56128. this.particleEmitterType = particleEmitter;
  56129. this.direction1 = direction1;
  56130. this.direction2 = direction2;
  56131. this.minEmitBox = minEmitBox;
  56132. this.maxEmitBox = maxEmitBox;
  56133. return particleEmitter;
  56134. };
  56135. /**
  56136. * Source color is added to the destination color without alpha affecting the result.
  56137. */
  56138. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  56139. /**
  56140. * Blend current color and particle color using particle’s alpha.
  56141. */
  56142. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  56143. /**
  56144. * Add current color and particle color multiplied by particle’s alpha.
  56145. */
  56146. BaseParticleSystem.BLENDMODE_ADD = 2;
  56147. /**
  56148. * Multiply current color with particle color
  56149. */
  56150. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  56151. return BaseParticleSystem;
  56152. }());
  56153. BABYLON.BaseParticleSystem = BaseParticleSystem;
  56154. })(BABYLON || (BABYLON = {}));
  56155. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  56156. var BABYLON;
  56157. (function (BABYLON) {
  56158. /**
  56159. * This represents a particle system in Babylon.
  56160. * 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.
  56161. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56162. * @example https://doc.babylonjs.com/babylon101/particles
  56163. */
  56164. var ParticleSystem = /** @class */ (function (_super) {
  56165. __extends(ParticleSystem, _super);
  56166. /**
  56167. * Instantiates a particle system.
  56168. * 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.
  56169. * @param name The name of the particle system
  56170. * @param capacity The max number of particles alive at the same time
  56171. * @param scene The scene the particle system belongs to
  56172. * @param customEffect a custom effect used to change the way particles are rendered by default
  56173. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56174. * @param epsilon Offset used to render the particles
  56175. */
  56176. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56177. if (customEffect === void 0) { customEffect = null; }
  56178. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56179. if (epsilon === void 0) { epsilon = 0.01; }
  56180. var _this = _super.call(this, name) || this;
  56181. /**
  56182. * An event triggered when the system is disposed
  56183. */
  56184. _this.onDisposeObservable = new BABYLON.Observable();
  56185. _this._particles = new Array();
  56186. _this._stockParticles = new Array();
  56187. _this._newPartsExcess = 0;
  56188. _this._vertexBuffers = {};
  56189. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56190. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56191. _this._scaledDirection = BABYLON.Vector3.Zero();
  56192. _this._scaledGravity = BABYLON.Vector3.Zero();
  56193. _this._currentRenderId = -1;
  56194. _this._useInstancing = false;
  56195. _this._started = false;
  56196. _this._stopped = false;
  56197. _this._actualFrame = 0;
  56198. /** @hidden */
  56199. _this._currentEmitRate1 = 0;
  56200. /** @hidden */
  56201. _this._currentEmitRate2 = 0;
  56202. // start of sub system methods
  56203. /**
  56204. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56205. * Its lifetime will start back at 0.
  56206. */
  56207. _this.recycleParticle = function (particle) {
  56208. var lastParticle = _this._particles.pop();
  56209. if (lastParticle !== particle) {
  56210. lastParticle.copyTo(particle);
  56211. }
  56212. _this._stockParticles.push(lastParticle);
  56213. };
  56214. _this._createParticle = function () {
  56215. var particle;
  56216. if (_this._stockParticles.length !== 0) {
  56217. particle = _this._stockParticles.pop();
  56218. particle.age = 0;
  56219. particle._currentColorGradient = null;
  56220. particle.cellIndex = _this.startSpriteCellID;
  56221. }
  56222. else {
  56223. particle = new BABYLON.Particle(_this);
  56224. }
  56225. return particle;
  56226. };
  56227. _this._emitFromParticle = function (particle) {
  56228. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56229. return;
  56230. }
  56231. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56232. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56233. subSystem._rootParticleSystem = _this;
  56234. _this.activeSubSystems.push(subSystem);
  56235. subSystem.start();
  56236. };
  56237. _this._capacity = capacity;
  56238. _this._epsilon = epsilon;
  56239. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56240. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56241. // Setup the default processing configuration to the scene.
  56242. _this._attachImageProcessingConfiguration(null);
  56243. _this._customEffect = customEffect;
  56244. _this._scene.particleSystems.push(_this);
  56245. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  56246. _this._createIndexBuffer();
  56247. _this._createVertexBuffers();
  56248. // Default emitter type
  56249. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56250. _this.updateFunction = function (particles) {
  56251. var noiseTextureData = null;
  56252. var noiseTextureSize = null;
  56253. if (_this.noiseTexture) { // We need to get texture data back to CPU
  56254. noiseTextureData = (_this.noiseTexture.readPixels());
  56255. noiseTextureSize = _this.noiseTexture.getSize();
  56256. }
  56257. var _loop_1 = function () {
  56258. particle = particles[index];
  56259. particle.age += _this._scaledUpdateSpeed;
  56260. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56261. _this._emitFromParticle(particle);
  56262. _this.recycleParticle(particle);
  56263. index--;
  56264. return "continue";
  56265. }
  56266. else {
  56267. var ratio = particle.age / particle.lifeTime;
  56268. // Color
  56269. if (_this._colorGradients && _this._colorGradients.length > 0) {
  56270. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  56271. if (currentGradient !== particle._currentColorGradient) {
  56272. particle._currentColor1.copyFrom(particle._currentColor2);
  56273. nextGradient.getColorToRef(particle._currentColor2);
  56274. particle._currentColorGradient = currentGradient;
  56275. }
  56276. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  56277. });
  56278. }
  56279. else {
  56280. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56281. particle.color.addInPlace(_this._scaledColorStep);
  56282. if (particle.color.a < 0) {
  56283. particle.color.a = 0;
  56284. }
  56285. }
  56286. // Angular speed
  56287. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  56288. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  56289. if (currentGradient !== particle._currentAngularSpeedGradient) {
  56290. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  56291. particle._currentAngularSpeed2 = nextGradient.getFactor();
  56292. particle._currentAngularSpeedGradient = currentGradient;
  56293. }
  56294. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  56295. });
  56296. }
  56297. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56298. // Direction
  56299. var directionScale_1 = _this._scaledUpdateSpeed;
  56300. /// Velocity
  56301. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  56302. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  56303. if (currentGradient !== particle._currentVelocityGradient) {
  56304. particle._currentVelocity1 = particle._currentVelocity2;
  56305. particle._currentVelocity2 = nextGradient.getFactor();
  56306. particle._currentVelocityGradient = currentGradient;
  56307. }
  56308. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  56309. });
  56310. }
  56311. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  56312. /// Limit velocity
  56313. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  56314. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  56315. if (currentGradient !== particle._currentLimitVelocityGradient) {
  56316. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  56317. particle._currentLimitVelocity2 = nextGradient.getFactor();
  56318. particle._currentLimitVelocityGradient = currentGradient;
  56319. }
  56320. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  56321. var currentVelocity = particle.direction.length();
  56322. if (currentVelocity > limitVelocity) {
  56323. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  56324. }
  56325. });
  56326. }
  56327. /// Drag
  56328. if (_this._dragGradients && _this._dragGradients.length > 0) {
  56329. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  56330. if (currentGradient !== particle._currentDragGradient) {
  56331. particle._currentDrag1 = particle._currentDrag2;
  56332. particle._currentDrag2 = nextGradient.getFactor();
  56333. particle._currentDragGradient = currentGradient;
  56334. }
  56335. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  56336. _this._scaledDirection.scaleInPlace(drag);
  56337. });
  56338. }
  56339. particle.position.addInPlace(_this._scaledDirection);
  56340. // Noise
  56341. if (noiseTextureData && noiseTextureSize) {
  56342. var localPosition = BABYLON.Tmp.Vector3[0];
  56343. var emitterPosition = BABYLON.Tmp.Vector3[1];
  56344. _this._emitterWorldMatrix.getTranslationToRef(emitterPosition);
  56345. particle.position.subtractToRef(emitterPosition, localPosition);
  56346. var fetchedColorR = _this._fetchR(localPosition.y, localPosition.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56347. var fetchedColorG = _this._fetchR(localPosition.x + 0.33, localPosition.z + 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56348. var fetchedColorB = _this._fetchR(localPosition.x - 0.33, localPosition.y - 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56349. var force = BABYLON.Tmp.Vector3[0];
  56350. var scaledForce = BABYLON.Tmp.Vector3[1];
  56351. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  56352. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  56353. particle.direction.addInPlace(scaledForce);
  56354. }
  56355. // Gravity
  56356. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56357. particle.direction.addInPlace(_this._scaledGravity);
  56358. // Size
  56359. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  56360. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  56361. if (currentGradient !== particle._currentSizeGradient) {
  56362. particle._currentSize1 = particle._currentSize2;
  56363. particle._currentSize2 = nextGradient.getFactor();
  56364. particle._currentSizeGradient = currentGradient;
  56365. }
  56366. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  56367. });
  56368. }
  56369. if (_this._isAnimationSheetEnabled) {
  56370. particle.updateCellIndex();
  56371. }
  56372. }
  56373. };
  56374. var particle;
  56375. for (var index = 0; index < particles.length; index++) {
  56376. _loop_1();
  56377. }
  56378. };
  56379. return _this;
  56380. }
  56381. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56382. /**
  56383. * Sets a callback that will be triggered when the system is disposed
  56384. */
  56385. set: function (callback) {
  56386. if (this._onDisposeObserver) {
  56387. this.onDisposeObservable.remove(this._onDisposeObserver);
  56388. }
  56389. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56390. },
  56391. enumerable: true,
  56392. configurable: true
  56393. });
  56394. /**
  56395. * Get hosting scene
  56396. * @returns the scene
  56397. */
  56398. ParticleSystem.prototype.getScene = function () {
  56399. return this._scene;
  56400. };
  56401. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56402. //end of Sub-emitter
  56403. /**
  56404. * Gets the current list of active particles
  56405. */
  56406. get: function () {
  56407. return this._particles;
  56408. },
  56409. enumerable: true,
  56410. configurable: true
  56411. });
  56412. /**
  56413. * Returns the string "ParticleSystem"
  56414. * @returns a string containing the class name
  56415. */
  56416. ParticleSystem.prototype.getClassName = function () {
  56417. return "ParticleSystem";
  56418. };
  56419. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  56420. var newGradient = new BABYLON.FactorGradient();
  56421. newGradient.gradient = gradient;
  56422. newGradient.factor1 = factor;
  56423. newGradient.factor2 = factor2;
  56424. factorGradients.push(newGradient);
  56425. factorGradients.sort(function (a, b) {
  56426. if (a.gradient < b.gradient) {
  56427. return -1;
  56428. }
  56429. else if (a.gradient > b.gradient) {
  56430. return 1;
  56431. }
  56432. return 0;
  56433. });
  56434. };
  56435. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  56436. if (!factorGradients) {
  56437. return;
  56438. }
  56439. var index = 0;
  56440. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  56441. var factorGradient = factorGradients_1[_i];
  56442. if (factorGradient.gradient === gradient) {
  56443. factorGradients.splice(index, 1);
  56444. break;
  56445. }
  56446. index++;
  56447. }
  56448. };
  56449. /**
  56450. * Adds a new life time gradient
  56451. * @param gradient defines the gradient to use (between 0 and 1)
  56452. * @param factor defines the life time factor to affect to the specified gradient
  56453. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56454. * @returns the current particle system
  56455. */
  56456. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  56457. if (!this._lifeTimeGradients) {
  56458. this._lifeTimeGradients = [];
  56459. }
  56460. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  56461. return this;
  56462. };
  56463. /**
  56464. * Remove a specific life time gradient
  56465. * @param gradient defines the gradient to remove
  56466. * @returns the current particle system
  56467. */
  56468. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  56469. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  56470. return this;
  56471. };
  56472. /**
  56473. * Adds a new size gradient
  56474. * @param gradient defines the gradient to use (between 0 and 1)
  56475. * @param factor defines the size factor to affect to the specified gradient
  56476. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56477. * @returns the current particle system
  56478. */
  56479. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  56480. if (!this._sizeGradients) {
  56481. this._sizeGradients = [];
  56482. }
  56483. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  56484. return this;
  56485. };
  56486. /**
  56487. * Remove a specific size gradient
  56488. * @param gradient defines the gradient to remove
  56489. * @returns the current particle system
  56490. */
  56491. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  56492. this._removeFactorGradient(this._sizeGradients, gradient);
  56493. return this;
  56494. };
  56495. /**
  56496. * Adds a new angular speed gradient
  56497. * @param gradient defines the gradient to use (between 0 and 1)
  56498. * @param factor defines the angular speed to affect to the specified gradient
  56499. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56500. * @returns the current particle system
  56501. */
  56502. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  56503. if (!this._angularSpeedGradients) {
  56504. this._angularSpeedGradients = [];
  56505. }
  56506. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  56507. return this;
  56508. };
  56509. /**
  56510. * Remove a specific angular speed gradient
  56511. * @param gradient defines the gradient to remove
  56512. * @returns the current particle system
  56513. */
  56514. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  56515. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  56516. return this;
  56517. };
  56518. /**
  56519. * Adds a new velocity gradient
  56520. * @param gradient defines the gradient to use (between 0 and 1)
  56521. * @param factor defines the velocity to affect to the specified gradient
  56522. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56523. * @returns the current particle system
  56524. */
  56525. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  56526. if (!this._velocityGradients) {
  56527. this._velocityGradients = [];
  56528. }
  56529. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  56530. return this;
  56531. };
  56532. /**
  56533. * Remove a specific velocity gradient
  56534. * @param gradient defines the gradient to remove
  56535. * @returns the current particle system
  56536. */
  56537. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  56538. this._removeFactorGradient(this._velocityGradients, gradient);
  56539. return this;
  56540. };
  56541. /**
  56542. * Adds a new limit velocity gradient
  56543. * @param gradient defines the gradient to use (between 0 and 1)
  56544. * @param factor defines the limit velocity value to affect to the specified gradient
  56545. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56546. * @returns the current particle system
  56547. */
  56548. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  56549. if (!this._limitVelocityGradients) {
  56550. this._limitVelocityGradients = [];
  56551. }
  56552. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  56553. return this;
  56554. };
  56555. /**
  56556. * Remove a specific limit velocity gradient
  56557. * @param gradient defines the gradient to remove
  56558. * @returns the current particle system
  56559. */
  56560. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  56561. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  56562. return this;
  56563. };
  56564. /**
  56565. * Adds a new drag gradient
  56566. * @param gradient defines the gradient to use (between 0 and 1)
  56567. * @param factor defines the drag value to affect to the specified gradient
  56568. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56569. * @returns the current particle system
  56570. */
  56571. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  56572. if (!this._dragGradients) {
  56573. this._dragGradients = [];
  56574. }
  56575. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  56576. return this;
  56577. };
  56578. /**
  56579. * Remove a specific drag gradient
  56580. * @param gradient defines the gradient to remove
  56581. * @returns the current particle system
  56582. */
  56583. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  56584. this._removeFactorGradient(this._dragGradients, gradient);
  56585. return this;
  56586. };
  56587. /**
  56588. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  56589. * @param gradient defines the gradient to use (between 0 and 1)
  56590. * @param factor defines the emit rate value to affect to the specified gradient
  56591. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56592. * @returns the current particle system
  56593. */
  56594. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  56595. if (!this._emitRateGradients) {
  56596. this._emitRateGradients = [];
  56597. }
  56598. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  56599. if (!this._currentEmitRateGradient) {
  56600. this._currentEmitRateGradient = this._emitRateGradients[0];
  56601. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  56602. this._currentEmitRate2 = this._currentEmitRate1;
  56603. }
  56604. if (this._emitRateGradients.length === 2) {
  56605. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  56606. }
  56607. return this;
  56608. };
  56609. /**
  56610. * Remove a specific emit rate gradient
  56611. * @param gradient defines the gradient to remove
  56612. * @returns the current particle system
  56613. */
  56614. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  56615. this._removeFactorGradient(this._emitRateGradients, gradient);
  56616. return this;
  56617. };
  56618. /**
  56619. * Adds a new color gradient
  56620. * @param gradient defines the gradient to use (between 0 and 1)
  56621. * @param color defines the color to affect to the specified gradient
  56622. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  56623. */
  56624. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  56625. if (!this._colorGradients) {
  56626. this._colorGradients = [];
  56627. }
  56628. var colorGradient = new BABYLON.ColorGradient();
  56629. colorGradient.gradient = gradient;
  56630. colorGradient.color1 = color;
  56631. colorGradient.color2 = color2;
  56632. this._colorGradients.push(colorGradient);
  56633. this._colorGradients.sort(function (a, b) {
  56634. if (a.gradient < b.gradient) {
  56635. return -1;
  56636. }
  56637. else if (a.gradient > b.gradient) {
  56638. return 1;
  56639. }
  56640. return 0;
  56641. });
  56642. return this;
  56643. };
  56644. /**
  56645. * Remove a specific color gradient
  56646. * @param gradient defines the gradient to remove
  56647. */
  56648. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  56649. if (!this._colorGradients) {
  56650. return this;
  56651. }
  56652. var index = 0;
  56653. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  56654. var colorGradient = _a[_i];
  56655. if (colorGradient.gradient === gradient) {
  56656. this._colorGradients.splice(index, 1);
  56657. break;
  56658. }
  56659. index++;
  56660. }
  56661. return this;
  56662. };
  56663. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  56664. u = Math.abs(u) * 0.5 + 0.5;
  56665. v = Math.abs(v) * 0.5 + 0.5;
  56666. var wrappedU = ((u * width) % width) | 0;
  56667. var wrappedV = ((v * height) % height) | 0;
  56668. var position = (wrappedU + wrappedV * width) * 4;
  56669. return pixels[position] / 255;
  56670. };
  56671. ParticleSystem.prototype._reset = function () {
  56672. this._resetEffect();
  56673. };
  56674. ParticleSystem.prototype._resetEffect = function () {
  56675. if (this._vertexBuffer) {
  56676. this._vertexBuffer.dispose();
  56677. this._vertexBuffer = null;
  56678. }
  56679. if (this._spriteBuffer) {
  56680. this._spriteBuffer.dispose();
  56681. this._spriteBuffer = null;
  56682. }
  56683. this._createVertexBuffers();
  56684. };
  56685. ParticleSystem.prototype._createVertexBuffers = function () {
  56686. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  56687. if (this._isAnimationSheetEnabled) {
  56688. this._vertexBufferSize += 1;
  56689. }
  56690. if (!this._isBillboardBased) {
  56691. this._vertexBufferSize += 3;
  56692. }
  56693. var engine = this._scene.getEngine();
  56694. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  56695. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  56696. var dataOffset = 0;
  56697. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56698. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56699. dataOffset += 3;
  56700. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56701. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56702. dataOffset += 4;
  56703. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56704. this._vertexBuffers["angle"] = options;
  56705. dataOffset += 1;
  56706. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56707. this._vertexBuffers["size"] = size;
  56708. dataOffset += 2;
  56709. if (this._isAnimationSheetEnabled) {
  56710. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56711. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56712. dataOffset += 1;
  56713. }
  56714. if (!this._isBillboardBased) {
  56715. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56716. this._vertexBuffers["direction"] = directionBuffer;
  56717. dataOffset += 3;
  56718. }
  56719. var offsets;
  56720. if (this._useInstancing) {
  56721. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  56722. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  56723. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  56724. }
  56725. else {
  56726. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56727. dataOffset += 2;
  56728. }
  56729. this._vertexBuffers["offset"] = offsets;
  56730. };
  56731. ParticleSystem.prototype._createIndexBuffer = function () {
  56732. if (this._useInstancing) {
  56733. return;
  56734. }
  56735. var indices = [];
  56736. var index = 0;
  56737. for (var count = 0; count < this._capacity; count++) {
  56738. indices.push(index);
  56739. indices.push(index + 1);
  56740. indices.push(index + 2);
  56741. indices.push(index);
  56742. indices.push(index + 2);
  56743. indices.push(index + 3);
  56744. index += 4;
  56745. }
  56746. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56747. };
  56748. /**
  56749. * Gets the maximum number of particles active at the same time.
  56750. * @returns The max number of active particles.
  56751. */
  56752. ParticleSystem.prototype.getCapacity = function () {
  56753. return this._capacity;
  56754. };
  56755. /**
  56756. * Gets whether there are still active particles in the system.
  56757. * @returns True if it is alive, otherwise false.
  56758. */
  56759. ParticleSystem.prototype.isAlive = function () {
  56760. return this._alive;
  56761. };
  56762. /**
  56763. * Gets if the system has been started. (Note: this will still be true after stop is called)
  56764. * @returns True if it has been started, otherwise false.
  56765. */
  56766. ParticleSystem.prototype.isStarted = function () {
  56767. return this._started;
  56768. };
  56769. /**
  56770. * Starts the particle system and begins to emit
  56771. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  56772. */
  56773. ParticleSystem.prototype.start = function (delay) {
  56774. var _this = this;
  56775. if (delay === void 0) { delay = 0; }
  56776. if (delay) {
  56777. setTimeout(function () {
  56778. _this.start(0);
  56779. }, delay);
  56780. return;
  56781. }
  56782. this._started = true;
  56783. this._stopped = false;
  56784. this._actualFrame = 0;
  56785. if (this.subEmitters && this.subEmitters.length != 0) {
  56786. this.activeSubSystems = new Array();
  56787. }
  56788. if (this.preWarmCycles) {
  56789. for (var index = 0; index < this.preWarmCycles; index++) {
  56790. this.animate(true);
  56791. }
  56792. }
  56793. };
  56794. /**
  56795. * Stops the particle system.
  56796. * @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.
  56797. */
  56798. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56799. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56800. this._stopped = true;
  56801. if (stopSubEmitters) {
  56802. this._stopSubEmitters();
  56803. }
  56804. };
  56805. // animation sheet
  56806. /**
  56807. * Remove all active particles
  56808. */
  56809. ParticleSystem.prototype.reset = function () {
  56810. this._stockParticles = [];
  56811. this._particles = [];
  56812. };
  56813. /**
  56814. * @hidden (for internal use only)
  56815. */
  56816. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56817. var offset = index * this._vertexBufferSize;
  56818. this._vertexData[offset++] = particle.position.x;
  56819. this._vertexData[offset++] = particle.position.y;
  56820. this._vertexData[offset++] = particle.position.z;
  56821. this._vertexData[offset++] = particle.color.r;
  56822. this._vertexData[offset++] = particle.color.g;
  56823. this._vertexData[offset++] = particle.color.b;
  56824. this._vertexData[offset++] = particle.color.a;
  56825. this._vertexData[offset++] = particle.angle;
  56826. this._vertexData[offset++] = particle.scale.x * particle.size;
  56827. this._vertexData[offset++] = particle.scale.y * particle.size;
  56828. if (this._isAnimationSheetEnabled) {
  56829. this._vertexData[offset++] = particle.cellIndex;
  56830. }
  56831. if (!this._isBillboardBased) {
  56832. if (particle._initialDirection) {
  56833. this._vertexData[offset++] = particle._initialDirection.x;
  56834. this._vertexData[offset++] = particle._initialDirection.y;
  56835. this._vertexData[offset++] = particle._initialDirection.z;
  56836. }
  56837. else {
  56838. this._vertexData[offset++] = particle.direction.x;
  56839. this._vertexData[offset++] = particle.direction.y;
  56840. this._vertexData[offset++] = particle.direction.z;
  56841. }
  56842. }
  56843. if (!this._useInstancing) {
  56844. if (this._isAnimationSheetEnabled) {
  56845. if (offsetX === 0)
  56846. offsetX = this._epsilon;
  56847. else if (offsetX === 1)
  56848. offsetX = 1 - this._epsilon;
  56849. if (offsetY === 0)
  56850. offsetY = this._epsilon;
  56851. else if (offsetY === 1)
  56852. offsetY = 1 - this._epsilon;
  56853. }
  56854. this._vertexData[offset++] = offsetX;
  56855. this._vertexData[offset++] = offsetY;
  56856. }
  56857. };
  56858. ParticleSystem.prototype._stopSubEmitters = function () {
  56859. if (!this.activeSubSystems) {
  56860. return;
  56861. }
  56862. this.activeSubSystems.forEach(function (subSystem) {
  56863. subSystem.stop(true);
  56864. });
  56865. this.activeSubSystems = new Array();
  56866. };
  56867. ParticleSystem.prototype._removeFromRoot = function () {
  56868. if (!this._rootParticleSystem) {
  56869. return;
  56870. }
  56871. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56872. if (index !== -1) {
  56873. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56874. }
  56875. };
  56876. // End of sub system methods
  56877. ParticleSystem.prototype._update = function (newParticles) {
  56878. // Update current
  56879. this._alive = this._particles.length > 0;
  56880. if (this.emitter.position) {
  56881. var emitterMesh = this.emitter;
  56882. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  56883. }
  56884. else {
  56885. var emitterPosition = this.emitter;
  56886. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56887. }
  56888. this.updateFunction(this._particles);
  56889. // Add new ones
  56890. var particle;
  56891. var _loop_2 = function () {
  56892. if (this_1._particles.length === this_1._capacity) {
  56893. return "break";
  56894. }
  56895. particle = this_1._createParticle();
  56896. this_1._particles.push(particle);
  56897. // Emitter
  56898. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  56899. if (this_1.startPositionFunction) {
  56900. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56901. }
  56902. else {
  56903. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56904. }
  56905. if (this_1.startDirectionFunction) {
  56906. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56907. }
  56908. else {
  56909. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56910. }
  56911. if (emitPower === 0) {
  56912. if (!particle._initialDirection) {
  56913. particle._initialDirection = particle.direction.clone();
  56914. }
  56915. else {
  56916. particle._initialDirection.copyFrom(particle.direction);
  56917. }
  56918. }
  56919. else {
  56920. particle._initialDirection = null;
  56921. }
  56922. particle.direction.scaleInPlace(emitPower);
  56923. // Life time
  56924. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  56925. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  56926. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  56927. var factorGradient1 = currentGradient;
  56928. var factorGradient2 = nextGradient;
  56929. var lifeTime1 = factorGradient1.getFactor();
  56930. var lifeTime2 = factorGradient2.getFactor();
  56931. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  56932. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  56933. });
  56934. }
  56935. else {
  56936. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  56937. }
  56938. // Size
  56939. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  56940. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  56941. }
  56942. else {
  56943. particle._currentSizeGradient = this_1._sizeGradients[0];
  56944. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  56945. particle.size = particle._currentSize1;
  56946. if (this_1._sizeGradients.length > 1) {
  56947. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  56948. }
  56949. else {
  56950. particle._currentSize2 = particle._currentSize1;
  56951. }
  56952. }
  56953. // Size and scale
  56954. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  56955. // Angle
  56956. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  56957. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  56958. }
  56959. else {
  56960. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  56961. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  56962. particle._currentAngularSpeed1 = particle.angularSpeed;
  56963. if (this_1._angularSpeedGradients.length > 1) {
  56964. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  56965. }
  56966. else {
  56967. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  56968. }
  56969. }
  56970. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  56971. // Velocity
  56972. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  56973. particle._currentVelocityGradient = this_1._velocityGradients[0];
  56974. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  56975. if (this_1._velocityGradients.length > 1) {
  56976. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  56977. }
  56978. else {
  56979. particle._currentVelocity2 = particle._currentVelocity1;
  56980. }
  56981. }
  56982. // Limit velocity
  56983. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  56984. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  56985. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  56986. if (this_1._limitVelocityGradients.length > 1) {
  56987. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  56988. }
  56989. else {
  56990. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  56991. }
  56992. }
  56993. // Drag
  56994. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  56995. particle._currentDragGradient = this_1._dragGradients[0];
  56996. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  56997. if (this_1._dragGradients.length > 1) {
  56998. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  56999. }
  57000. else {
  57001. particle._currentDrag2 = particle._currentDrag1;
  57002. }
  57003. }
  57004. // Color
  57005. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  57006. step = BABYLON.Scalar.RandomRange(0, 1.0);
  57007. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  57008. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  57009. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  57010. }
  57011. else {
  57012. particle._currentColorGradient = this_1._colorGradients[0];
  57013. particle._currentColorGradient.getColorToRef(particle.color);
  57014. particle._currentColor1.copyFrom(particle.color);
  57015. if (this_1._colorGradients.length > 1) {
  57016. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  57017. }
  57018. else {
  57019. particle._currentColor2.copyFrom(particle.color);
  57020. }
  57021. }
  57022. // Sheet
  57023. if (this_1._isAnimationSheetEnabled) {
  57024. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  57025. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  57026. }
  57027. };
  57028. var this_1 = this, step;
  57029. for (var index = 0; index < newParticles; index++) {
  57030. var state_1 = _loop_2();
  57031. if (state_1 === "break")
  57032. break;
  57033. }
  57034. };
  57035. /** @hidden */
  57036. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  57037. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57038. if (isBillboardBased === void 0) { isBillboardBased = false; }
  57039. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  57040. if (isAnimationSheetEnabled) {
  57041. attributeNamesOrOptions.push("cellIndex");
  57042. }
  57043. if (!isBillboardBased) {
  57044. attributeNamesOrOptions.push("direction");
  57045. }
  57046. return attributeNamesOrOptions;
  57047. };
  57048. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  57049. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57050. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  57051. if (isAnimationSheetEnabled) {
  57052. effectCreationOption.push("particlesInfos");
  57053. }
  57054. return effectCreationOption;
  57055. };
  57056. ParticleSystem.prototype._getEffect = function () {
  57057. if (this._customEffect) {
  57058. return this._customEffect;
  57059. }
  57060. ;
  57061. var defines = [];
  57062. if (this._scene.clipPlane) {
  57063. defines.push("#define CLIPPLANE");
  57064. }
  57065. if (this._scene.clipPlane2) {
  57066. defines.push("#define CLIPPLANE2");
  57067. }
  57068. if (this._scene.clipPlane3) {
  57069. defines.push("#define CLIPPLANE3");
  57070. }
  57071. if (this._scene.clipPlane4) {
  57072. defines.push("#define CLIPPLANE4");
  57073. }
  57074. if (this._isAnimationSheetEnabled) {
  57075. defines.push("#define ANIMATESHEET");
  57076. }
  57077. if (this._isBillboardBased) {
  57078. defines.push("#define BILLBOARD");
  57079. switch (this.billboardMode) {
  57080. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  57081. defines.push("#define BILLBOARDY");
  57082. break;
  57083. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  57084. default:
  57085. break;
  57086. }
  57087. }
  57088. if (this._imageProcessingConfiguration) {
  57089. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  57090. defines.push(this._imageProcessingConfigurationDefines.toString());
  57091. }
  57092. // Effect
  57093. var join = defines.join("\n");
  57094. if (this._cachedDefines !== join) {
  57095. this._cachedDefines = join;
  57096. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  57097. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  57098. var samplers = ["diffuseSampler"];
  57099. if (BABYLON.ImageProcessingConfiguration) {
  57100. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  57101. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  57102. }
  57103. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  57104. }
  57105. return this._effect;
  57106. };
  57107. /**
  57108. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57109. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  57110. */
  57111. ParticleSystem.prototype.animate = function (preWarmOnly) {
  57112. var _this = this;
  57113. if (preWarmOnly === void 0) { preWarmOnly = false; }
  57114. if (!this._started)
  57115. return;
  57116. if (!preWarmOnly) {
  57117. var effect = this._getEffect();
  57118. // Check
  57119. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  57120. return;
  57121. if (this._currentRenderId === this._scene.getRenderId()) {
  57122. return;
  57123. }
  57124. this._currentRenderId = this._scene.getRenderId();
  57125. }
  57126. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57127. // Determine the number of particles we need to create
  57128. var newParticles;
  57129. if (this.manualEmitCount > -1) {
  57130. newParticles = this.manualEmitCount;
  57131. this._newPartsExcess = 0;
  57132. this.manualEmitCount = 0;
  57133. }
  57134. else {
  57135. var rate_1 = this.emitRate;
  57136. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  57137. var ratio = this._actualFrame / this.targetStopDuration;
  57138. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  57139. if (currentGradient !== _this._currentEmitRateGradient) {
  57140. _this._currentEmitRate1 = _this._currentEmitRate2;
  57141. _this._currentEmitRate2 = nextGradient.getFactor();
  57142. _this._currentEmitRateGradient = currentGradient;
  57143. }
  57144. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  57145. });
  57146. }
  57147. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  57148. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  57149. }
  57150. if (this._newPartsExcess > 1.0) {
  57151. newParticles += this._newPartsExcess >> 0;
  57152. this._newPartsExcess -= this._newPartsExcess >> 0;
  57153. }
  57154. this._alive = false;
  57155. if (!this._stopped) {
  57156. this._actualFrame += this._scaledUpdateSpeed;
  57157. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  57158. this.stop();
  57159. }
  57160. else {
  57161. newParticles = 0;
  57162. }
  57163. this._update(newParticles);
  57164. // Stopped?
  57165. if (this._stopped) {
  57166. if (!this._alive) {
  57167. this._started = false;
  57168. if (this.onAnimationEnd) {
  57169. this.onAnimationEnd();
  57170. }
  57171. if (this.disposeOnStop) {
  57172. this._scene._toBeDisposed.push(this);
  57173. }
  57174. }
  57175. }
  57176. if (!preWarmOnly) {
  57177. // Update VBO
  57178. var offset = 0;
  57179. for (var index = 0; index < this._particles.length; index++) {
  57180. var particle = this._particles[index];
  57181. this._appendParticleVertices(offset, particle);
  57182. offset += this._useInstancing ? 1 : 4;
  57183. }
  57184. if (this._vertexBuffer) {
  57185. this._vertexBuffer.update(this._vertexData);
  57186. }
  57187. }
  57188. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  57189. this.stop();
  57190. }
  57191. };
  57192. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  57193. this._appendParticleVertex(offset++, particle, 0, 0);
  57194. if (!this._useInstancing) {
  57195. this._appendParticleVertex(offset++, particle, 1, 0);
  57196. this._appendParticleVertex(offset++, particle, 1, 1);
  57197. this._appendParticleVertex(offset++, particle, 0, 1);
  57198. }
  57199. };
  57200. /**
  57201. * Rebuilds the particle system.
  57202. */
  57203. ParticleSystem.prototype.rebuild = function () {
  57204. this._createIndexBuffer();
  57205. if (this._vertexBuffer) {
  57206. this._vertexBuffer._rebuild();
  57207. }
  57208. };
  57209. /**
  57210. * Is this system ready to be used/rendered
  57211. * @return true if the system is ready
  57212. */
  57213. ParticleSystem.prototype.isReady = function () {
  57214. var effect = this._getEffect();
  57215. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57216. return false;
  57217. }
  57218. return true;
  57219. };
  57220. /**
  57221. * Renders the particle system in its current state.
  57222. * @returns the current number of particles
  57223. */
  57224. ParticleSystem.prototype.render = function () {
  57225. var effect = this._getEffect();
  57226. // Check
  57227. if (!this.isReady() || !this._particles.length) {
  57228. return 0;
  57229. }
  57230. var engine = this._scene.getEngine();
  57231. // Render
  57232. engine.enableEffect(effect);
  57233. engine.setState(false);
  57234. var viewMatrix = this._scene.getViewMatrix();
  57235. effect.setTexture("diffuseSampler", this.particleTexture);
  57236. effect.setMatrix("view", viewMatrix);
  57237. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  57238. if (this._isAnimationSheetEnabled && this.particleTexture) {
  57239. var baseSize = this.particleTexture.getBaseSize();
  57240. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  57241. }
  57242. effect.setVector2("translationPivot", this.translationPivot);
  57243. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  57244. if (this._isBillboardBased) {
  57245. var camera = this._scene.activeCamera;
  57246. effect.setVector3("eyePosition", camera.globalPosition);
  57247. }
  57248. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  57249. var invView = viewMatrix.clone();
  57250. invView.invert();
  57251. effect.setMatrix("invView", invView);
  57252. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  57253. }
  57254. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  57255. // image processing
  57256. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  57257. this._imageProcessingConfiguration.bind(effect);
  57258. }
  57259. // Draw order
  57260. switch (this.blendMode) {
  57261. case ParticleSystem.BLENDMODE_ADD:
  57262. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57263. break;
  57264. case ParticleSystem.BLENDMODE_ONEONE:
  57265. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57266. break;
  57267. case ParticleSystem.BLENDMODE_STANDARD:
  57268. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57269. break;
  57270. case ParticleSystem.BLENDMODE_MULTIPLY:
  57271. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  57272. break;
  57273. }
  57274. if (this.forceDepthWrite) {
  57275. engine.setDepthWrite(true);
  57276. }
  57277. if (this._useInstancing) {
  57278. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  57279. engine.unbindInstanceAttributes();
  57280. }
  57281. else {
  57282. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  57283. }
  57284. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57285. return this._particles.length;
  57286. };
  57287. /**
  57288. * Disposes the particle system and free the associated resources
  57289. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57290. */
  57291. ParticleSystem.prototype.dispose = function (disposeTexture) {
  57292. if (disposeTexture === void 0) { disposeTexture = true; }
  57293. if (this._vertexBuffer) {
  57294. this._vertexBuffer.dispose();
  57295. this._vertexBuffer = null;
  57296. }
  57297. if (this._spriteBuffer) {
  57298. this._spriteBuffer.dispose();
  57299. this._spriteBuffer = null;
  57300. }
  57301. if (this._indexBuffer) {
  57302. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57303. this._indexBuffer = null;
  57304. }
  57305. if (disposeTexture && this.particleTexture) {
  57306. this.particleTexture.dispose();
  57307. this.particleTexture = null;
  57308. }
  57309. if (disposeTexture && this.noiseTexture) {
  57310. this.noiseTexture.dispose();
  57311. this.noiseTexture = null;
  57312. }
  57313. this._removeFromRoot();
  57314. // Remove from scene
  57315. var index = this._scene.particleSystems.indexOf(this);
  57316. if (index > -1) {
  57317. this._scene.particleSystems.splice(index, 1);
  57318. }
  57319. // Callback
  57320. this.onDisposeObservable.notifyObservers(this);
  57321. this.onDisposeObservable.clear();
  57322. };
  57323. // Clone
  57324. /**
  57325. * Clones the particle system.
  57326. * @param name The name of the cloned object
  57327. * @param newEmitter The new emitter to use
  57328. * @returns the cloned particle system
  57329. */
  57330. ParticleSystem.prototype.clone = function (name, newEmitter) {
  57331. var custom = null;
  57332. var program = null;
  57333. if (this.customShader != null) {
  57334. program = this.customShader;
  57335. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57336. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57337. }
  57338. else if (this._customEffect) {
  57339. custom = this._customEffect;
  57340. }
  57341. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  57342. result.customShader = program;
  57343. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  57344. if (newEmitter === undefined) {
  57345. newEmitter = this.emitter;
  57346. }
  57347. result.emitter = newEmitter;
  57348. if (this.particleTexture) {
  57349. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57350. }
  57351. if (!this.preventAutoStart) {
  57352. result.start();
  57353. }
  57354. return result;
  57355. };
  57356. /**
  57357. * Serializes the particle system to a JSON object.
  57358. * @returns the JSON object
  57359. */
  57360. ParticleSystem.prototype.serialize = function () {
  57361. var serializationObject = {};
  57362. ParticleSystem._Serialize(serializationObject, this);
  57363. serializationObject.textureMask = this.textureMask.asArray();
  57364. serializationObject.customShader = this.customShader;
  57365. serializationObject.preventAutoStart = this.preventAutoStart;
  57366. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  57367. return serializationObject;
  57368. };
  57369. /** @hidden */
  57370. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  57371. serializationObject.name = particleSystem.name;
  57372. serializationObject.id = particleSystem.id;
  57373. serializationObject.capacity = particleSystem.getCapacity();
  57374. // Emitter
  57375. if (particleSystem.emitter.position) {
  57376. var emitterMesh = particleSystem.emitter;
  57377. serializationObject.emitterId = emitterMesh.id;
  57378. }
  57379. else {
  57380. var emitterPosition = particleSystem.emitter;
  57381. serializationObject.emitter = emitterPosition.asArray();
  57382. }
  57383. // Emitter
  57384. if (particleSystem.particleEmitterType) {
  57385. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  57386. }
  57387. if (particleSystem.particleTexture) {
  57388. serializationObject.textureName = particleSystem.particleTexture.name;
  57389. }
  57390. // Animations
  57391. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  57392. // Particle system
  57393. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  57394. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  57395. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  57396. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  57397. serializationObject.minSize = particleSystem.minSize;
  57398. serializationObject.maxSize = particleSystem.maxSize;
  57399. serializationObject.minScaleX = particleSystem.minScaleX;
  57400. serializationObject.maxScaleX = particleSystem.maxScaleX;
  57401. serializationObject.minScaleY = particleSystem.minScaleY;
  57402. serializationObject.maxScaleY = particleSystem.maxScaleY;
  57403. serializationObject.minEmitPower = particleSystem.minEmitPower;
  57404. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  57405. serializationObject.minLifeTime = particleSystem.minLifeTime;
  57406. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  57407. serializationObject.emitRate = particleSystem.emitRate;
  57408. serializationObject.gravity = particleSystem.gravity.asArray();
  57409. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  57410. serializationObject.color1 = particleSystem.color1.asArray();
  57411. serializationObject.color2 = particleSystem.color2.asArray();
  57412. serializationObject.colorDead = particleSystem.colorDead.asArray();
  57413. serializationObject.updateSpeed = particleSystem.updateSpeed;
  57414. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  57415. serializationObject.blendMode = particleSystem.blendMode;
  57416. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  57417. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  57418. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  57419. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  57420. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  57421. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  57422. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  57423. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  57424. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  57425. var colorGradients = particleSystem.getColorGradients();
  57426. if (colorGradients) {
  57427. serializationObject.colorGradients = [];
  57428. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  57429. var colorGradient = colorGradients_1[_i];
  57430. var serializedGradient = {
  57431. gradient: colorGradient.gradient,
  57432. color1: colorGradient.color1.asArray()
  57433. };
  57434. if (colorGradient.color2) {
  57435. serializedGradient.color2 = colorGradient.color2.asArray();
  57436. }
  57437. serializationObject.colorGradients.push(serializedGradient);
  57438. }
  57439. }
  57440. var sizeGradients = particleSystem.getSizeGradients();
  57441. if (sizeGradients) {
  57442. serializationObject.sizeGradients = [];
  57443. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  57444. var sizeGradient = sizeGradients_1[_a];
  57445. var serializedGradient = {
  57446. gradient: sizeGradient.gradient,
  57447. factor1: sizeGradient.factor1
  57448. };
  57449. if (sizeGradient.factor2 !== undefined) {
  57450. serializedGradient.factor2 = sizeGradient.factor2;
  57451. }
  57452. serializationObject.sizeGradients.push(serializedGradient);
  57453. }
  57454. }
  57455. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  57456. if (angularSpeedGradients) {
  57457. serializationObject.angularSpeedGradients = [];
  57458. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  57459. var angularSpeedGradient = angularSpeedGradients_1[_b];
  57460. var serializedGradient = {
  57461. gradient: angularSpeedGradient.gradient,
  57462. factor1: angularSpeedGradient.factor1
  57463. };
  57464. if (angularSpeedGradient.factor2 !== undefined) {
  57465. serializedGradient.factor2 = angularSpeedGradient.factor2;
  57466. }
  57467. serializationObject.angularSpeedGradients.push(serializedGradient);
  57468. }
  57469. }
  57470. var velocityGradients = particleSystem.getVelocityGradients();
  57471. if (velocityGradients) {
  57472. serializationObject.velocityGradients = [];
  57473. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  57474. var velocityGradient = velocityGradients_1[_c];
  57475. var serializedGradient = {
  57476. gradient: velocityGradient.gradient,
  57477. factor1: velocityGradient.factor1
  57478. };
  57479. if (velocityGradient.factor2 !== undefined) {
  57480. serializedGradient.factor2 = velocityGradient.factor2;
  57481. }
  57482. serializationObject.velocityGradients.push(serializedGradient);
  57483. }
  57484. }
  57485. var dragGradients = particleSystem.getDragGradients();
  57486. if (dragGradients) {
  57487. serializationObject.dragyGradients = [];
  57488. for (var _d = 0, dragGradients_1 = dragGradients; _d < dragGradients_1.length; _d++) {
  57489. var dragGradient = dragGradients_1[_d];
  57490. var serializedGradient = {
  57491. gradient: dragGradient.gradient,
  57492. factor1: dragGradient.factor1
  57493. };
  57494. if (dragGradient.factor2 !== undefined) {
  57495. serializedGradient.factor2 = dragGradient.factor2;
  57496. }
  57497. serializationObject.dragGradients.push(serializedGradient);
  57498. }
  57499. }
  57500. var emitRateGradients = particleSystem.getEmitRateGradients();
  57501. if (emitRateGradients) {
  57502. serializationObject.emitRateGradients = [];
  57503. for (var _e = 0, emitRateGradients_1 = emitRateGradients; _e < emitRateGradients_1.length; _e++) {
  57504. var emitRateGradient = emitRateGradients_1[_e];
  57505. var serializedGradient = {
  57506. gradient: emitRateGradient.gradient,
  57507. factor1: emitRateGradient.factor1
  57508. };
  57509. if (emitRateGradient.factor2 !== undefined) {
  57510. serializedGradient.factor2 = emitRateGradient.factor2;
  57511. }
  57512. serializationObject.emitRateGradients.push(serializedGradient);
  57513. }
  57514. }
  57515. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  57516. if (limitVelocityGradients) {
  57517. serializationObject.limitVelocityGradients = [];
  57518. for (var _f = 0, limitVelocityGradients_1 = limitVelocityGradients; _f < limitVelocityGradients_1.length; _f++) {
  57519. var limitVelocityGradient = limitVelocityGradients_1[_f];
  57520. var serializedGradient = {
  57521. gradient: limitVelocityGradient.gradient,
  57522. factor1: limitVelocityGradient.factor1
  57523. };
  57524. if (limitVelocityGradient.factor2 !== undefined) {
  57525. serializedGradient.factor2 = limitVelocityGradient.factor2;
  57526. }
  57527. serializationObject.limitVelocityGradients.push(serializedGradient);
  57528. }
  57529. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  57530. }
  57531. if (particleSystem.noiseTexture && particleSystem.noiseTexture instanceof BABYLON.ProceduralTexture) {
  57532. var noiseTexture = particleSystem.noiseTexture;
  57533. serializationObject.noiseTexture = noiseTexture.serialize();
  57534. }
  57535. };
  57536. /** @hidden */
  57537. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  57538. // Texture
  57539. if (parsedParticleSystem.textureName) {
  57540. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57541. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57542. }
  57543. // Emitter
  57544. if (parsedParticleSystem.emitterId === undefined) {
  57545. particleSystem.emitter = BABYLON.Vector3.Zero();
  57546. }
  57547. else if (parsedParticleSystem.emitterId) {
  57548. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57549. }
  57550. else {
  57551. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57552. }
  57553. // Misc.
  57554. if (parsedParticleSystem.renderingGroupId !== undefined) {
  57555. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  57556. }
  57557. if (parsedParticleSystem.isBillboardBased !== undefined) {
  57558. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  57559. }
  57560. // Animations
  57561. if (parsedParticleSystem.animations) {
  57562. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57563. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57564. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57565. }
  57566. }
  57567. if (parsedParticleSystem.autoAnimate) {
  57568. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57569. }
  57570. // Particle system
  57571. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57572. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57573. particleSystem.minSize = parsedParticleSystem.minSize;
  57574. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57575. if (parsedParticleSystem.minScaleX) {
  57576. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  57577. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  57578. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  57579. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  57580. }
  57581. if (parsedParticleSystem.preWarmCycles !== undefined) {
  57582. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  57583. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  57584. }
  57585. if (parsedParticleSystem.minInitialRotation !== undefined) {
  57586. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  57587. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  57588. }
  57589. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57590. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57591. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57592. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57593. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57594. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57595. if (parsedParticleSystem.noiseStrength) {
  57596. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  57597. }
  57598. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57599. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57600. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57601. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57602. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57603. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57604. if (parsedParticleSystem.colorGradients) {
  57605. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  57606. var colorGradient = _a[_i];
  57607. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  57608. }
  57609. }
  57610. if (parsedParticleSystem.sizeGradients) {
  57611. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  57612. var sizeGradient = _c[_b];
  57613. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  57614. }
  57615. }
  57616. if (parsedParticleSystem.angularSpeedGradients) {
  57617. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  57618. var angularSpeedGradient = _e[_d];
  57619. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  57620. }
  57621. }
  57622. if (parsedParticleSystem.velocityGradients) {
  57623. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  57624. var velocityGradient = _g[_f];
  57625. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  57626. }
  57627. }
  57628. if (parsedParticleSystem.dragGradients) {
  57629. for (var _h = 0, _j = parsedParticleSystem.dragGradients; _h < _j.length; _h++) {
  57630. var dragGradient = _j[_h];
  57631. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  57632. }
  57633. }
  57634. if (parsedParticleSystem.emitRateGradients) {
  57635. for (var _k = 0, _l = parsedParticleSystem.emitRateGradients; _k < _l.length; _k++) {
  57636. var emitRateGradient = _l[_k];
  57637. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  57638. }
  57639. }
  57640. if (parsedParticleSystem.limitVelocityGradients) {
  57641. for (var _m = 0, _o = parsedParticleSystem.limitVelocityGradients; _m < _o.length; _m++) {
  57642. var limitVelocityGradient = _o[_m];
  57643. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  57644. }
  57645. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  57646. }
  57647. if (parsedParticleSystem.noiseTexture) {
  57648. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  57649. }
  57650. // Emitter
  57651. var emitterType;
  57652. if (parsedParticleSystem.particleEmitterType) {
  57653. switch (parsedParticleSystem.particleEmitterType.type) {
  57654. case "SphereParticleEmitter":
  57655. emitterType = new BABYLON.SphereParticleEmitter();
  57656. break;
  57657. case "SphereDirectedParticleEmitter":
  57658. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57659. break;
  57660. case "ConeEmitter":
  57661. case "ConeParticleEmitter":
  57662. emitterType = new BABYLON.ConeParticleEmitter();
  57663. break;
  57664. case "BoxEmitter":
  57665. case "BoxParticleEmitter":
  57666. default:
  57667. emitterType = new BABYLON.BoxParticleEmitter();
  57668. break;
  57669. }
  57670. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57671. }
  57672. else {
  57673. emitterType = new BABYLON.BoxParticleEmitter();
  57674. emitterType.parse(parsedParticleSystem);
  57675. }
  57676. particleSystem.particleEmitterType = emitterType;
  57677. // Animation sheet
  57678. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  57679. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  57680. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  57681. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  57682. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  57683. };
  57684. /**
  57685. * Parses a JSON object to create a particle system.
  57686. * @param parsedParticleSystem The JSON object to parse
  57687. * @param scene The scene to create the particle system in
  57688. * @param rootUrl The root url to use to load external dependencies like texture
  57689. * @returns the Parsed particle system
  57690. */
  57691. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57692. var name = parsedParticleSystem.name;
  57693. var custom = null;
  57694. var program = null;
  57695. if (parsedParticleSystem.customShader) {
  57696. program = parsedParticleSystem.customShader;
  57697. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57698. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57699. }
  57700. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  57701. particleSystem.customShader = program;
  57702. if (parsedParticleSystem.id) {
  57703. particleSystem.id = parsedParticleSystem.id;
  57704. }
  57705. // Auto start
  57706. if (parsedParticleSystem.preventAutoStart) {
  57707. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  57708. }
  57709. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  57710. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57711. if (!particleSystem.preventAutoStart) {
  57712. particleSystem.start();
  57713. }
  57714. return particleSystem;
  57715. };
  57716. return ParticleSystem;
  57717. }(BABYLON.BaseParticleSystem));
  57718. BABYLON.ParticleSystem = ParticleSystem;
  57719. })(BABYLON || (BABYLON = {}));
  57720. //# sourceMappingURL=babylon.particleSystem.js.map
  57721. var BABYLON;
  57722. (function (BABYLON) {
  57723. /**
  57724. * Particle emitter emitting particles from the inside of a box.
  57725. * It emits the particles randomly between 2 given directions.
  57726. */
  57727. var BoxParticleEmitter = /** @class */ (function () {
  57728. /**
  57729. * Creates a new instance BoxParticleEmitter
  57730. */
  57731. function BoxParticleEmitter() {
  57732. /**
  57733. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57734. */
  57735. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57736. /**
  57737. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57738. */
  57739. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57740. /**
  57741. * 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.
  57742. */
  57743. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  57744. /**
  57745. * 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.
  57746. */
  57747. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  57748. }
  57749. /**
  57750. * Called by the particle System when the direction is computed for the created particle.
  57751. * @param worldMatrix is the world matrix of the particle system
  57752. * @param directionToUpdate is the direction vector to update with the result
  57753. * @param particle is the particle we are computed the direction for
  57754. */
  57755. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57756. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57757. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57758. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57759. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57760. };
  57761. /**
  57762. * Called by the particle System when the position is computed for the created particle.
  57763. * @param worldMatrix is the world matrix of the particle system
  57764. * @param positionToUpdate is the position vector to update with the result
  57765. * @param particle is the particle we are computed the position for
  57766. */
  57767. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57768. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  57769. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  57770. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  57771. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57772. };
  57773. /**
  57774. * Clones the current emitter and returns a copy of it
  57775. * @returns the new emitter
  57776. */
  57777. BoxParticleEmitter.prototype.clone = function () {
  57778. var newOne = new BoxParticleEmitter();
  57779. BABYLON.Tools.DeepCopy(this, newOne);
  57780. return newOne;
  57781. };
  57782. /**
  57783. * Called by the GPUParticleSystem to setup the update shader
  57784. * @param effect defines the update shader
  57785. */
  57786. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  57787. effect.setVector3("direction1", this.direction1);
  57788. effect.setVector3("direction2", this.direction2);
  57789. effect.setVector3("minEmitBox", this.minEmitBox);
  57790. effect.setVector3("maxEmitBox", this.maxEmitBox);
  57791. };
  57792. /**
  57793. * Returns a string to use to update the GPU particles update shader
  57794. * @returns a string containng the defines string
  57795. */
  57796. BoxParticleEmitter.prototype.getEffectDefines = function () {
  57797. return "#define BOXEMITTER";
  57798. };
  57799. /**
  57800. * Returns the string "BoxParticleEmitter"
  57801. * @returns a string containing the class name
  57802. */
  57803. BoxParticleEmitter.prototype.getClassName = function () {
  57804. return "BoxParticleEmitter";
  57805. };
  57806. /**
  57807. * Serializes the particle system to a JSON object.
  57808. * @returns the JSON object
  57809. */
  57810. BoxParticleEmitter.prototype.serialize = function () {
  57811. var serializationObject = {};
  57812. serializationObject.type = this.getClassName();
  57813. serializationObject.direction1 = this.direction1.asArray();
  57814. serializationObject.direction2 = this.direction2.asArray();
  57815. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57816. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57817. return serializationObject;
  57818. };
  57819. /**
  57820. * Parse properties from a JSON object
  57821. * @param serializationObject defines the JSON object
  57822. */
  57823. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  57824. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  57825. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  57826. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  57827. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  57828. };
  57829. return BoxParticleEmitter;
  57830. }());
  57831. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57832. })(BABYLON || (BABYLON = {}));
  57833. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57834. var BABYLON;
  57835. (function (BABYLON) {
  57836. /**
  57837. * Particle emitter emitting particles from the inside of a cylinder.
  57838. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  57839. */
  57840. var CylinderParticleEmitter = /** @class */ (function () {
  57841. /**
  57842. * Creates a new instance CylinderParticleEmitter
  57843. * @param radius the radius of the emission cylinder (1 by default)
  57844. * @param height the height of the emission cylinder (1 by default)
  57845. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57846. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57847. */
  57848. function CylinderParticleEmitter(
  57849. /**
  57850. * The radius of the emission cylinder.
  57851. */
  57852. radius,
  57853. /**
  57854. * The height of the emission cylinder.
  57855. */
  57856. height,
  57857. /**
  57858. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  57859. */
  57860. radiusRange,
  57861. /**
  57862. * How much to randomize the particle direction [0-1].
  57863. */
  57864. directionRandomizer) {
  57865. if (radius === void 0) { radius = 1; }
  57866. if (height === void 0) { height = 1; }
  57867. if (radiusRange === void 0) { radiusRange = 1; }
  57868. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57869. this.radius = radius;
  57870. this.height = height;
  57871. this.radiusRange = radiusRange;
  57872. this.directionRandomizer = directionRandomizer;
  57873. }
  57874. /**
  57875. * Called by the particle System when the direction is computed for the created particle.
  57876. * @param worldMatrix is the world matrix of the particle system
  57877. * @param directionToUpdate is the direction vector to update with the result
  57878. * @param particle is the particle we are computed the direction for
  57879. */
  57880. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57881. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57882. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  57883. var angle = Math.atan2(direction.x, direction.z);
  57884. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  57885. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  57886. direction.x = Math.sin(angle);
  57887. direction.z = Math.cos(angle);
  57888. direction.normalize();
  57889. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  57890. };
  57891. /**
  57892. * Called by the particle System when the position is computed for the created particle.
  57893. * @param worldMatrix is the world matrix of the particle system
  57894. * @param positionToUpdate is the position vector to update with the result
  57895. * @param particle is the particle we are computed the position for
  57896. */
  57897. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57898. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  57899. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57900. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  57901. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  57902. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  57903. var xPos = positionRadius * Math.cos(angle);
  57904. var zPos = positionRadius * Math.sin(angle);
  57905. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  57906. };
  57907. /**
  57908. * Clones the current emitter and returns a copy of it
  57909. * @returns the new emitter
  57910. */
  57911. CylinderParticleEmitter.prototype.clone = function () {
  57912. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  57913. BABYLON.Tools.DeepCopy(this, newOne);
  57914. return newOne;
  57915. };
  57916. /**
  57917. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57918. * @param effect defines the update shader
  57919. */
  57920. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  57921. effect.setFloat("radius", this.radius);
  57922. effect.setFloat("height", this.height);
  57923. effect.setFloat("radiusRange", this.radiusRange);
  57924. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57925. };
  57926. /**
  57927. * Returns a string to use to update the GPU particles update shader
  57928. * @returns a string containng the defines string
  57929. */
  57930. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  57931. return "#define CYLINDEREMITTER";
  57932. };
  57933. /**
  57934. * Returns the string "CylinderParticleEmitter"
  57935. * @returns a string containing the class name
  57936. */
  57937. CylinderParticleEmitter.prototype.getClassName = function () {
  57938. return "CylinderParticleEmitter";
  57939. };
  57940. /**
  57941. * Serializes the particle system to a JSON object.
  57942. * @returns the JSON object
  57943. */
  57944. CylinderParticleEmitter.prototype.serialize = function () {
  57945. var serializationObject = {};
  57946. serializationObject.type = this.getClassName();
  57947. serializationObject.radius = this.radius;
  57948. serializationObject.height = this.height;
  57949. serializationObject.radiusRange = this.radiusRange;
  57950. serializationObject.directionRandomizer = this.directionRandomizer;
  57951. return serializationObject;
  57952. };
  57953. /**
  57954. * Parse properties from a JSON object
  57955. * @param serializationObject defines the JSON object
  57956. */
  57957. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  57958. this.radius = serializationObject.radius;
  57959. this.height = serializationObject.height;
  57960. this.radiusRange = serializationObject.radiusRange;
  57961. this.directionRandomizer = serializationObject.directionRandomizer;
  57962. };
  57963. return CylinderParticleEmitter;
  57964. }());
  57965. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  57966. })(BABYLON || (BABYLON = {}));
  57967. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  57968. var BABYLON;
  57969. (function (BABYLON) {
  57970. /**
  57971. * Particle emitter emitting particles from the inside of a cone.
  57972. * It emits the particles alongside the cone volume from the base to the particle.
  57973. * The emission direction might be randomized.
  57974. */
  57975. var ConeParticleEmitter = /** @class */ (function () {
  57976. /**
  57977. * Creates a new instance ConeParticleEmitter
  57978. * @param radius the radius of the emission cone (1 by default)
  57979. * @param angles the cone base angle (PI by default)
  57980. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  57981. */
  57982. function ConeParticleEmitter(radius, angle,
  57983. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  57984. directionRandomizer) {
  57985. if (radius === void 0) { radius = 1; }
  57986. if (angle === void 0) { angle = Math.PI; }
  57987. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57988. this.directionRandomizer = directionRandomizer;
  57989. /**
  57990. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  57991. */
  57992. this.radiusRange = 1;
  57993. /**
  57994. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  57995. */
  57996. this.heightRange = 1;
  57997. /**
  57998. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  57999. */
  58000. this.emitFromSpawnPointOnly = false;
  58001. this.angle = angle;
  58002. this.radius = radius;
  58003. }
  58004. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  58005. /**
  58006. * Gets or sets the radius of the emission cone
  58007. */
  58008. get: function () {
  58009. return this._radius;
  58010. },
  58011. set: function (value) {
  58012. this._radius = value;
  58013. this._buildHeight();
  58014. },
  58015. enumerable: true,
  58016. configurable: true
  58017. });
  58018. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  58019. /**
  58020. * Gets or sets the angle of the emission cone
  58021. */
  58022. get: function () {
  58023. return this._angle;
  58024. },
  58025. set: function (value) {
  58026. this._angle = value;
  58027. this._buildHeight();
  58028. },
  58029. enumerable: true,
  58030. configurable: true
  58031. });
  58032. ConeParticleEmitter.prototype._buildHeight = function () {
  58033. if (this._angle !== 0) {
  58034. this._height = this._radius / Math.tan(this._angle / 2);
  58035. }
  58036. else {
  58037. this._height = 1;
  58038. }
  58039. };
  58040. /**
  58041. * Called by the particle System when the direction is computed for the created particle.
  58042. * @param worldMatrix is the world matrix of the particle system
  58043. * @param directionToUpdate is the direction vector to update with the result
  58044. * @param particle is the particle we are computed the direction for
  58045. */
  58046. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58047. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  58048. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  58049. }
  58050. else {
  58051. // measure the direction Vector from the emitter to the particle.
  58052. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58053. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58054. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58055. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58056. direction.x += randX;
  58057. direction.y += randY;
  58058. direction.z += randZ;
  58059. direction.normalize();
  58060. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58061. }
  58062. };
  58063. /**
  58064. * Called by the particle System when the position is computed for the created particle.
  58065. * @param worldMatrix is the world matrix of the particle system
  58066. * @param positionToUpdate is the position vector to update with the result
  58067. * @param particle is the particle we are computed the position for
  58068. */
  58069. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58070. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  58071. var h;
  58072. if (!this.emitFromSpawnPointOnly) {
  58073. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  58074. // Better distribution in a cone at normal angles.
  58075. h = 1 - h * h;
  58076. }
  58077. else {
  58078. h = 0.0001;
  58079. }
  58080. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  58081. radius = radius * h;
  58082. var randX = radius * Math.sin(s);
  58083. var randZ = radius * Math.cos(s);
  58084. var randY = h * this._height;
  58085. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58086. };
  58087. /**
  58088. * Clones the current emitter and returns a copy of it
  58089. * @returns the new emitter
  58090. */
  58091. ConeParticleEmitter.prototype.clone = function () {
  58092. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  58093. BABYLON.Tools.DeepCopy(this, newOne);
  58094. return newOne;
  58095. };
  58096. /**
  58097. * Called by the GPUParticleSystem to setup the update shader
  58098. * @param effect defines the update shader
  58099. */
  58100. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  58101. effect.setFloat2("radius", this._radius, this.radiusRange);
  58102. effect.setFloat("coneAngle", this._angle);
  58103. effect.setFloat2("height", this._height, this.heightRange);
  58104. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58105. };
  58106. /**
  58107. * Returns a string to use to update the GPU particles update shader
  58108. * @returns a string containng the defines string
  58109. */
  58110. ConeParticleEmitter.prototype.getEffectDefines = function () {
  58111. var defines = "#define CONEEMITTER";
  58112. if (this.emitFromSpawnPointOnly) {
  58113. defines += "\n#define CONEEMITTERSPAWNPOINT";
  58114. }
  58115. return defines;
  58116. };
  58117. /**
  58118. * Returns the string "ConeParticleEmitter"
  58119. * @returns a string containing the class name
  58120. */
  58121. ConeParticleEmitter.prototype.getClassName = function () {
  58122. return "ConeParticleEmitter";
  58123. };
  58124. /**
  58125. * Serializes the particle system to a JSON object.
  58126. * @returns the JSON object
  58127. */
  58128. ConeParticleEmitter.prototype.serialize = function () {
  58129. var serializationObject = {};
  58130. serializationObject.type = this.getClassName();
  58131. serializationObject.radius = this._radius;
  58132. serializationObject.angle = this._angle;
  58133. serializationObject.directionRandomizer = this.directionRandomizer;
  58134. return serializationObject;
  58135. };
  58136. /**
  58137. * Parse properties from a JSON object
  58138. * @param serializationObject defines the JSON object
  58139. */
  58140. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  58141. this.radius = serializationObject.radius;
  58142. this.angle = serializationObject.angle;
  58143. this.directionRandomizer = serializationObject.directionRandomizer;
  58144. };
  58145. return ConeParticleEmitter;
  58146. }());
  58147. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  58148. })(BABYLON || (BABYLON = {}));
  58149. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  58150. var BABYLON;
  58151. (function (BABYLON) {
  58152. /**
  58153. * Particle emitter emitting particles from the inside of a sphere.
  58154. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  58155. */
  58156. var SphereParticleEmitter = /** @class */ (function () {
  58157. /**
  58158. * Creates a new instance SphereParticleEmitter
  58159. * @param radius the radius of the emission sphere (1 by default)
  58160. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58161. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58162. */
  58163. function SphereParticleEmitter(
  58164. /**
  58165. * The radius of the emission sphere.
  58166. */
  58167. radius,
  58168. /**
  58169. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58170. */
  58171. radiusRange,
  58172. /**
  58173. * How much to randomize the particle direction [0-1].
  58174. */
  58175. directionRandomizer) {
  58176. if (radius === void 0) { radius = 1; }
  58177. if (radiusRange === void 0) { radiusRange = 1; }
  58178. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58179. this.radius = radius;
  58180. this.radiusRange = radiusRange;
  58181. this.directionRandomizer = directionRandomizer;
  58182. }
  58183. /**
  58184. * Called by the particle System when the direction is computed for the created particle.
  58185. * @param worldMatrix is the world matrix of the particle system
  58186. * @param directionToUpdate is the direction vector to update with the result
  58187. * @param particle is the particle we are computed the direction for
  58188. */
  58189. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58190. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58191. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58192. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58193. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58194. direction.x += randX;
  58195. direction.y += randY;
  58196. direction.z += randZ;
  58197. direction.normalize();
  58198. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58199. };
  58200. /**
  58201. * Called by the particle System when the position is computed for the created particle.
  58202. * @param worldMatrix is the world matrix of the particle system
  58203. * @param positionToUpdate is the position vector to update with the result
  58204. * @param particle is the particle we are computed the position for
  58205. */
  58206. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58207. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58208. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58209. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58210. var theta = Math.acos(2 * v - 1);
  58211. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58212. var randY = randRadius * Math.cos(theta);
  58213. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58214. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58215. };
  58216. /**
  58217. * Clones the current emitter and returns a copy of it
  58218. * @returns the new emitter
  58219. */
  58220. SphereParticleEmitter.prototype.clone = function () {
  58221. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  58222. BABYLON.Tools.DeepCopy(this, newOne);
  58223. return newOne;
  58224. };
  58225. /**
  58226. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58227. * @param effect defines the update shader
  58228. */
  58229. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  58230. effect.setFloat("radius", this.radius);
  58231. effect.setFloat("radiusRange", this.radiusRange);
  58232. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58233. };
  58234. /**
  58235. * Returns a string to use to update the GPU particles update shader
  58236. * @returns a string containng the defines string
  58237. */
  58238. SphereParticleEmitter.prototype.getEffectDefines = function () {
  58239. return "#define SPHEREEMITTER";
  58240. };
  58241. /**
  58242. * Returns the string "SphereParticleEmitter"
  58243. * @returns a string containing the class name
  58244. */
  58245. SphereParticleEmitter.prototype.getClassName = function () {
  58246. return "SphereParticleEmitter";
  58247. };
  58248. /**
  58249. * Serializes the particle system to a JSON object.
  58250. * @returns the JSON object
  58251. */
  58252. SphereParticleEmitter.prototype.serialize = function () {
  58253. var serializationObject = {};
  58254. serializationObject.type = this.getClassName();
  58255. serializationObject.radius = this.radius;
  58256. serializationObject.radiusRange = this.radiusRange;
  58257. serializationObject.directionRandomizer = this.directionRandomizer;
  58258. return serializationObject;
  58259. };
  58260. /**
  58261. * Parse properties from a JSON object
  58262. * @param serializationObject defines the JSON object
  58263. */
  58264. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  58265. this.radius = serializationObject.radius;
  58266. this.radiusRange = serializationObject.radiusRange;
  58267. this.directionRandomizer = serializationObject.directionRandomizer;
  58268. };
  58269. return SphereParticleEmitter;
  58270. }());
  58271. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  58272. /**
  58273. * Particle emitter emitting particles from the inside of a sphere.
  58274. * It emits the particles randomly between two vectors.
  58275. */
  58276. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  58277. __extends(SphereDirectedParticleEmitter, _super);
  58278. /**
  58279. * Creates a new instance SphereDirectedParticleEmitter
  58280. * @param radius the radius of the emission sphere (1 by default)
  58281. * @param direction1 the min limit of the emission direction (up vector by default)
  58282. * @param direction2 the max limit of the emission direction (up vector by default)
  58283. */
  58284. function SphereDirectedParticleEmitter(radius,
  58285. /**
  58286. * The min limit of the emission direction.
  58287. */
  58288. direction1,
  58289. /**
  58290. * The max limit of the emission direction.
  58291. */
  58292. direction2) {
  58293. if (radius === void 0) { radius = 1; }
  58294. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58295. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58296. var _this = _super.call(this, radius) || this;
  58297. _this.direction1 = direction1;
  58298. _this.direction2 = direction2;
  58299. return _this;
  58300. }
  58301. /**
  58302. * Called by the particle System when the direction is computed for the created particle.
  58303. * @param worldMatrix is the world matrix of the particle system
  58304. * @param directionToUpdate is the direction vector to update with the result
  58305. * @param particle is the particle we are computed the direction for
  58306. */
  58307. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58308. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58309. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58310. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58311. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58312. };
  58313. /**
  58314. * Clones the current emitter and returns a copy of it
  58315. * @returns the new emitter
  58316. */
  58317. SphereDirectedParticleEmitter.prototype.clone = function () {
  58318. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  58319. BABYLON.Tools.DeepCopy(this, newOne);
  58320. return newOne;
  58321. };
  58322. /**
  58323. * Called by the GPUParticleSystem to setup the update shader
  58324. * @param effect defines the update shader
  58325. */
  58326. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58327. effect.setFloat("radius", this.radius);
  58328. effect.setFloat("radiusRange", this.radiusRange);
  58329. effect.setVector3("direction1", this.direction1);
  58330. effect.setVector3("direction2", this.direction2);
  58331. };
  58332. /**
  58333. * Returns a string to use to update the GPU particles update shader
  58334. * @returns a string containng the defines string
  58335. */
  58336. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58337. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  58338. };
  58339. /**
  58340. * Returns the string "SphereDirectedParticleEmitter"
  58341. * @returns a string containing the class name
  58342. */
  58343. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  58344. return "SphereDirectedParticleEmitter";
  58345. };
  58346. /**
  58347. * Serializes the particle system to a JSON object.
  58348. * @returns the JSON object
  58349. */
  58350. SphereDirectedParticleEmitter.prototype.serialize = function () {
  58351. var serializationObject = _super.prototype.serialize.call(this);
  58352. serializationObject.direction1 = this.direction1.asArray();
  58353. serializationObject.direction2 = this.direction2.asArray();
  58354. return serializationObject;
  58355. };
  58356. /**
  58357. * Parse properties from a JSON object
  58358. * @param serializationObject defines the JSON object
  58359. */
  58360. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58361. _super.prototype.parse.call(this, serializationObject);
  58362. this.direction1.copyFrom(serializationObject.direction1);
  58363. this.direction2.copyFrom(serializationObject.direction2);
  58364. };
  58365. return SphereDirectedParticleEmitter;
  58366. }(SphereParticleEmitter));
  58367. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  58368. })(BABYLON || (BABYLON = {}));
  58369. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  58370. var BABYLON;
  58371. (function (BABYLON) {
  58372. /**
  58373. * Particle emitter emitting particles from the inside of a hemisphere.
  58374. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  58375. */
  58376. var HemisphericParticleEmitter = /** @class */ (function () {
  58377. /**
  58378. * Creates a new instance HemisphericParticleEmitter
  58379. * @param radius the radius of the emission hemisphere (1 by default)
  58380. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58381. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58382. */
  58383. function HemisphericParticleEmitter(
  58384. /**
  58385. * The radius of the emission hemisphere.
  58386. */
  58387. radius,
  58388. /**
  58389. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58390. */
  58391. radiusRange,
  58392. /**
  58393. * How much to randomize the particle direction [0-1].
  58394. */
  58395. directionRandomizer) {
  58396. if (radius === void 0) { radius = 1; }
  58397. if (radiusRange === void 0) { radiusRange = 1; }
  58398. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58399. this.radius = radius;
  58400. this.radiusRange = radiusRange;
  58401. this.directionRandomizer = directionRandomizer;
  58402. }
  58403. /**
  58404. * Called by the particle System when the direction is computed for the created particle.
  58405. * @param worldMatrix is the world matrix of the particle system
  58406. * @param directionToUpdate is the direction vector to update with the result
  58407. * @param particle is the particle we are computed the direction for
  58408. */
  58409. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58410. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58411. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58412. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58413. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58414. direction.x += randX;
  58415. direction.y += randY;
  58416. direction.z += randZ;
  58417. direction.normalize();
  58418. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58419. };
  58420. /**
  58421. * Called by the particle System when the position is computed for the created particle.
  58422. * @param worldMatrix is the world matrix of the particle system
  58423. * @param positionToUpdate is the position vector to update with the result
  58424. * @param particle is the particle we are computed the position for
  58425. */
  58426. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58427. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58428. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58429. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58430. var theta = Math.acos(2 * v - 1);
  58431. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58432. var randY = randRadius * Math.cos(theta);
  58433. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58434. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  58435. };
  58436. /**
  58437. * Clones the current emitter and returns a copy of it
  58438. * @returns the new emitter
  58439. */
  58440. HemisphericParticleEmitter.prototype.clone = function () {
  58441. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  58442. BABYLON.Tools.DeepCopy(this, newOne);
  58443. return newOne;
  58444. };
  58445. /**
  58446. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58447. * @param effect defines the update shader
  58448. */
  58449. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  58450. effect.setFloat("radius", this.radius);
  58451. effect.setFloat("radiusRange", this.radiusRange);
  58452. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58453. };
  58454. /**
  58455. * Returns a string to use to update the GPU particles update shader
  58456. * @returns a string containng the defines string
  58457. */
  58458. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  58459. return "#define HEMISPHERICEMITTER";
  58460. };
  58461. /**
  58462. * Returns the string "HemisphericParticleEmitter"
  58463. * @returns a string containing the class name
  58464. */
  58465. HemisphericParticleEmitter.prototype.getClassName = function () {
  58466. return "HemisphericParticleEmitter";
  58467. };
  58468. /**
  58469. * Serializes the particle system to a JSON object.
  58470. * @returns the JSON object
  58471. */
  58472. HemisphericParticleEmitter.prototype.serialize = function () {
  58473. var serializationObject = {};
  58474. serializationObject.type = this.getClassName();
  58475. serializationObject.radius = this.radius;
  58476. serializationObject.radiusRange = this.radiusRange;
  58477. serializationObject.directionRandomizer = this.directionRandomizer;
  58478. return serializationObject;
  58479. };
  58480. /**
  58481. * Parse properties from a JSON object
  58482. * @param serializationObject defines the JSON object
  58483. */
  58484. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  58485. this.radius = serializationObject.radius;
  58486. this.radiusRange = serializationObject.radiusRange;
  58487. this.directionRandomizer = serializationObject.directionRandomizer;
  58488. };
  58489. return HemisphericParticleEmitter;
  58490. }());
  58491. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  58492. })(BABYLON || (BABYLON = {}));
  58493. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  58494. var BABYLON;
  58495. (function (BABYLON) {
  58496. /**
  58497. * Particle emitter emitting particles from a point.
  58498. * It emits the particles randomly between 2 given directions.
  58499. */
  58500. var PointParticleEmitter = /** @class */ (function () {
  58501. /**
  58502. * Creates a new instance PointParticleEmitter
  58503. */
  58504. function PointParticleEmitter() {
  58505. /**
  58506. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58507. */
  58508. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  58509. /**
  58510. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58511. */
  58512. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  58513. }
  58514. /**
  58515. * Called by the particle System when the direction is computed for the created particle.
  58516. * @param worldMatrix is the world matrix of the particle system
  58517. * @param directionToUpdate is the direction vector to update with the result
  58518. * @param particle is the particle we are computed the direction for
  58519. */
  58520. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58521. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58522. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58523. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58524. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58525. };
  58526. /**
  58527. * Called by the particle System when the position is computed for the created particle.
  58528. * @param worldMatrix is the world matrix of the particle system
  58529. * @param positionToUpdate is the position vector to update with the result
  58530. * @param particle is the particle we are computed the position for
  58531. */
  58532. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58533. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  58534. };
  58535. /**
  58536. * Clones the current emitter and returns a copy of it
  58537. * @returns the new emitter
  58538. */
  58539. PointParticleEmitter.prototype.clone = function () {
  58540. var newOne = new PointParticleEmitter();
  58541. BABYLON.Tools.DeepCopy(this, newOne);
  58542. return newOne;
  58543. };
  58544. /**
  58545. * Called by the GPUParticleSystem to setup the update shader
  58546. * @param effect defines the update shader
  58547. */
  58548. PointParticleEmitter.prototype.applyToShader = function (effect) {
  58549. effect.setVector3("direction1", this.direction1);
  58550. effect.setVector3("direction2", this.direction2);
  58551. };
  58552. /**
  58553. * Returns a string to use to update the GPU particles update shader
  58554. * @returns a string containng the defines string
  58555. */
  58556. PointParticleEmitter.prototype.getEffectDefines = function () {
  58557. return "#define POINTEMITTER";
  58558. };
  58559. /**
  58560. * Returns the string "PointParticleEmitter"
  58561. * @returns a string containing the class name
  58562. */
  58563. PointParticleEmitter.prototype.getClassName = function () {
  58564. return "PointParticleEmitter";
  58565. };
  58566. /**
  58567. * Serializes the particle system to a JSON object.
  58568. * @returns the JSON object
  58569. */
  58570. PointParticleEmitter.prototype.serialize = function () {
  58571. var serializationObject = {};
  58572. serializationObject.type = this.getClassName();
  58573. serializationObject.direction1 = this.direction1.asArray();
  58574. serializationObject.direction2 = this.direction2.asArray();
  58575. return serializationObject;
  58576. };
  58577. /**
  58578. * Parse properties from a JSON object
  58579. * @param serializationObject defines the JSON object
  58580. */
  58581. PointParticleEmitter.prototype.parse = function (serializationObject) {
  58582. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  58583. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  58584. };
  58585. return PointParticleEmitter;
  58586. }());
  58587. BABYLON.PointParticleEmitter = PointParticleEmitter;
  58588. })(BABYLON || (BABYLON = {}));
  58589. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  58590. var BABYLON;
  58591. (function (BABYLON) {
  58592. // Adds the parsers to the scene parsers.
  58593. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  58594. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  58595. if (!individualParser) {
  58596. return;
  58597. }
  58598. // Particles Systems
  58599. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  58600. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  58601. var parsedParticleSystem = parsedData.particleSystems[index];
  58602. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  58603. }
  58604. }
  58605. });
  58606. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  58607. if (parsedParticleSystem.activeParticleCount) {
  58608. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58609. return ps;
  58610. }
  58611. else {
  58612. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58613. return ps;
  58614. }
  58615. });
  58616. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  58617. if (uniformsNames === void 0) { uniformsNames = []; }
  58618. if (samplers === void 0) { samplers = []; }
  58619. if (defines === void 0) { defines = ""; }
  58620. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  58621. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  58622. if (defines.indexOf(" BILLBOARD") === -1) {
  58623. defines += "\n#define BILLBOARD\n";
  58624. }
  58625. if (samplers.indexOf("diffuseSampler") === -1) {
  58626. samplers.push("diffuseSampler");
  58627. }
  58628. return this.createEffect({
  58629. vertex: "particles",
  58630. fragmentElement: fragmentName
  58631. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  58632. };
  58633. })(BABYLON || (BABYLON = {}));
  58634. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  58635. var BABYLON;
  58636. (function (BABYLON) {
  58637. var ShaderMaterial = /** @class */ (function (_super) {
  58638. __extends(ShaderMaterial, _super);
  58639. function ShaderMaterial(name, scene, shaderPath, options) {
  58640. var _this = _super.call(this, name, scene) || this;
  58641. _this._textures = {};
  58642. _this._textureArrays = {};
  58643. _this._floats = {};
  58644. _this._ints = {};
  58645. _this._floatsArrays = {};
  58646. _this._colors3 = {};
  58647. _this._colors3Arrays = {};
  58648. _this._colors4 = {};
  58649. _this._vectors2 = {};
  58650. _this._vectors3 = {};
  58651. _this._vectors4 = {};
  58652. _this._matrices = {};
  58653. _this._matrices3x3 = {};
  58654. _this._matrices2x2 = {};
  58655. _this._vectors2Arrays = {};
  58656. _this._vectors3Arrays = {};
  58657. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  58658. _this._shaderPath = shaderPath;
  58659. options.needAlphaBlending = options.needAlphaBlending || false;
  58660. options.needAlphaTesting = options.needAlphaTesting || false;
  58661. options.attributes = options.attributes || ["position", "normal", "uv"];
  58662. options.uniforms = options.uniforms || ["worldViewProjection"];
  58663. options.uniformBuffers = options.uniformBuffers || [];
  58664. options.samplers = options.samplers || [];
  58665. options.defines = options.defines || [];
  58666. _this._options = options;
  58667. return _this;
  58668. }
  58669. ShaderMaterial.prototype.getClassName = function () {
  58670. return "ShaderMaterial";
  58671. };
  58672. ShaderMaterial.prototype.needAlphaBlending = function () {
  58673. return this._options.needAlphaBlending;
  58674. };
  58675. ShaderMaterial.prototype.needAlphaTesting = function () {
  58676. return this._options.needAlphaTesting;
  58677. };
  58678. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  58679. if (this._options.uniforms.indexOf(uniformName) === -1) {
  58680. this._options.uniforms.push(uniformName);
  58681. }
  58682. };
  58683. ShaderMaterial.prototype.setTexture = function (name, texture) {
  58684. if (this._options.samplers.indexOf(name) === -1) {
  58685. this._options.samplers.push(name);
  58686. }
  58687. this._textures[name] = texture;
  58688. return this;
  58689. };
  58690. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  58691. if (this._options.samplers.indexOf(name) === -1) {
  58692. this._options.samplers.push(name);
  58693. }
  58694. this._checkUniform(name);
  58695. this._textureArrays[name] = textures;
  58696. return this;
  58697. };
  58698. ShaderMaterial.prototype.setFloat = function (name, value) {
  58699. this._checkUniform(name);
  58700. this._floats[name] = value;
  58701. return this;
  58702. };
  58703. ShaderMaterial.prototype.setInt = function (name, value) {
  58704. this._checkUniform(name);
  58705. this._ints[name] = value;
  58706. return this;
  58707. };
  58708. ShaderMaterial.prototype.setFloats = function (name, value) {
  58709. this._checkUniform(name);
  58710. this._floatsArrays[name] = value;
  58711. return this;
  58712. };
  58713. ShaderMaterial.prototype.setColor3 = function (name, value) {
  58714. this._checkUniform(name);
  58715. this._colors3[name] = value;
  58716. return this;
  58717. };
  58718. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  58719. this._checkUniform(name);
  58720. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  58721. color.toArray(arr, arr.length);
  58722. return arr;
  58723. }, []);
  58724. return this;
  58725. };
  58726. ShaderMaterial.prototype.setColor4 = function (name, value) {
  58727. this._checkUniform(name);
  58728. this._colors4[name] = value;
  58729. return this;
  58730. };
  58731. ShaderMaterial.prototype.setVector2 = function (name, value) {
  58732. this._checkUniform(name);
  58733. this._vectors2[name] = value;
  58734. return this;
  58735. };
  58736. ShaderMaterial.prototype.setVector3 = function (name, value) {
  58737. this._checkUniform(name);
  58738. this._vectors3[name] = value;
  58739. return this;
  58740. };
  58741. ShaderMaterial.prototype.setVector4 = function (name, value) {
  58742. this._checkUniform(name);
  58743. this._vectors4[name] = value;
  58744. return this;
  58745. };
  58746. ShaderMaterial.prototype.setMatrix = function (name, value) {
  58747. this._checkUniform(name);
  58748. this._matrices[name] = value;
  58749. return this;
  58750. };
  58751. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  58752. this._checkUniform(name);
  58753. this._matrices3x3[name] = value;
  58754. return this;
  58755. };
  58756. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  58757. this._checkUniform(name);
  58758. this._matrices2x2[name] = value;
  58759. return this;
  58760. };
  58761. ShaderMaterial.prototype.setArray2 = function (name, value) {
  58762. this._checkUniform(name);
  58763. this._vectors2Arrays[name] = value;
  58764. return this;
  58765. };
  58766. ShaderMaterial.prototype.setArray3 = function (name, value) {
  58767. this._checkUniform(name);
  58768. this._vectors3Arrays[name] = value;
  58769. return this;
  58770. };
  58771. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58772. if (!mesh) {
  58773. return true;
  58774. }
  58775. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  58776. return false;
  58777. }
  58778. return false;
  58779. };
  58780. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  58781. var scene = this.getScene();
  58782. var engine = scene.getEngine();
  58783. if (!this.checkReadyOnEveryCall) {
  58784. if (this._renderId === scene.getRenderId()) {
  58785. if (this._checkCache(scene, mesh, useInstances)) {
  58786. return true;
  58787. }
  58788. }
  58789. }
  58790. // Instances
  58791. var defines = [];
  58792. var attribs = [];
  58793. var fallbacks = new BABYLON.EffectFallbacks();
  58794. if (useInstances) {
  58795. defines.push("#define INSTANCES");
  58796. }
  58797. for (var index = 0; index < this._options.defines.length; index++) {
  58798. defines.push(this._options.defines[index]);
  58799. }
  58800. for (var index = 0; index < this._options.attributes.length; index++) {
  58801. attribs.push(this._options.attributes[index]);
  58802. }
  58803. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58804. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58805. defines.push("#define VERTEXCOLOR");
  58806. }
  58807. // Bones
  58808. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58809. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58810. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58811. if (mesh.numBoneInfluencers > 4) {
  58812. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58813. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58814. }
  58815. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58816. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58817. fallbacks.addCPUSkinningFallback(0, mesh);
  58818. if (this._options.uniforms.indexOf("mBones") === -1) {
  58819. this._options.uniforms.push("mBones");
  58820. }
  58821. }
  58822. else {
  58823. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58824. }
  58825. // Textures
  58826. for (var name in this._textures) {
  58827. if (!this._textures[name].isReady()) {
  58828. return false;
  58829. }
  58830. }
  58831. // Alpha test
  58832. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  58833. defines.push("#define ALPHATEST");
  58834. }
  58835. var previousEffect = this._effect;
  58836. var join = defines.join("\n");
  58837. this._effect = engine.createEffect(this._shaderPath, {
  58838. attributes: attribs,
  58839. uniformsNames: this._options.uniforms,
  58840. uniformBuffersNames: this._options.uniformBuffers,
  58841. samplers: this._options.samplers,
  58842. defines: join,
  58843. fallbacks: fallbacks,
  58844. onCompiled: this.onCompiled,
  58845. onError: this.onError
  58846. }, engine);
  58847. if (!this._effect.isReady()) {
  58848. return false;
  58849. }
  58850. if (previousEffect !== this._effect) {
  58851. scene.resetCachedMaterial();
  58852. }
  58853. this._renderId = scene.getRenderId();
  58854. return true;
  58855. };
  58856. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58857. var scene = this.getScene();
  58858. if (!this._effect) {
  58859. return;
  58860. }
  58861. if (this._options.uniforms.indexOf("world") !== -1) {
  58862. this._effect.setMatrix("world", world);
  58863. }
  58864. if (this._options.uniforms.indexOf("worldView") !== -1) {
  58865. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  58866. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  58867. }
  58868. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  58869. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  58870. }
  58871. };
  58872. ShaderMaterial.prototype.bind = function (world, mesh) {
  58873. // Std values
  58874. this.bindOnlyWorldMatrix(world);
  58875. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  58876. if (this._options.uniforms.indexOf("view") !== -1) {
  58877. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  58878. }
  58879. if (this._options.uniforms.indexOf("projection") !== -1) {
  58880. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  58881. }
  58882. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  58883. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  58884. }
  58885. // Bones
  58886. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58887. var name;
  58888. // Texture
  58889. for (name in this._textures) {
  58890. this._effect.setTexture(name, this._textures[name]);
  58891. }
  58892. // Texture arrays
  58893. for (name in this._textureArrays) {
  58894. this._effect.setTextureArray(name, this._textureArrays[name]);
  58895. }
  58896. // Int
  58897. for (name in this._ints) {
  58898. this._effect.setInt(name, this._ints[name]);
  58899. }
  58900. // Float
  58901. for (name in this._floats) {
  58902. this._effect.setFloat(name, this._floats[name]);
  58903. }
  58904. // Floats
  58905. for (name in this._floatsArrays) {
  58906. this._effect.setArray(name, this._floatsArrays[name]);
  58907. }
  58908. // Color3
  58909. for (name in this._colors3) {
  58910. this._effect.setColor3(name, this._colors3[name]);
  58911. }
  58912. for (name in this._colors3Arrays) {
  58913. this._effect.setArray3(name, this._colors3Arrays[name]);
  58914. }
  58915. // Color4
  58916. for (name in this._colors4) {
  58917. var color = this._colors4[name];
  58918. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  58919. }
  58920. // Vector2
  58921. for (name in this._vectors2) {
  58922. this._effect.setVector2(name, this._vectors2[name]);
  58923. }
  58924. // Vector3
  58925. for (name in this._vectors3) {
  58926. this._effect.setVector3(name, this._vectors3[name]);
  58927. }
  58928. // Vector4
  58929. for (name in this._vectors4) {
  58930. this._effect.setVector4(name, this._vectors4[name]);
  58931. }
  58932. // Matrix
  58933. for (name in this._matrices) {
  58934. this._effect.setMatrix(name, this._matrices[name]);
  58935. }
  58936. // Matrix 3x3
  58937. for (name in this._matrices3x3) {
  58938. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  58939. }
  58940. // Matrix 2x2
  58941. for (name in this._matrices2x2) {
  58942. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  58943. }
  58944. // Vector2Array
  58945. for (name in this._vectors2Arrays) {
  58946. this._effect.setArray2(name, this._vectors2Arrays[name]);
  58947. }
  58948. // Vector3Array
  58949. for (name in this._vectors3Arrays) {
  58950. this._effect.setArray3(name, this._vectors3Arrays[name]);
  58951. }
  58952. }
  58953. this._afterBind(mesh);
  58954. };
  58955. ShaderMaterial.prototype.getActiveTextures = function () {
  58956. var activeTextures = _super.prototype.getActiveTextures.call(this);
  58957. for (var name in this._textures) {
  58958. activeTextures.push(this._textures[name]);
  58959. }
  58960. for (var name in this._textureArrays) {
  58961. var array = this._textureArrays[name];
  58962. for (var index = 0; index < array.length; index++) {
  58963. activeTextures.push(array[index]);
  58964. }
  58965. }
  58966. return activeTextures;
  58967. };
  58968. ShaderMaterial.prototype.hasTexture = function (texture) {
  58969. if (_super.prototype.hasTexture.call(this, texture)) {
  58970. return true;
  58971. }
  58972. for (var name in this._textures) {
  58973. if (this._textures[name] === texture) {
  58974. return true;
  58975. }
  58976. }
  58977. for (var name in this._textureArrays) {
  58978. var array = this._textureArrays[name];
  58979. for (var index = 0; index < array.length; index++) {
  58980. if (array[index] === texture) {
  58981. return true;
  58982. }
  58983. }
  58984. }
  58985. return false;
  58986. };
  58987. ShaderMaterial.prototype.clone = function (name) {
  58988. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  58989. return newShaderMaterial;
  58990. };
  58991. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58992. if (forceDisposeTextures) {
  58993. var name;
  58994. for (name in this._textures) {
  58995. this._textures[name].dispose();
  58996. }
  58997. for (name in this._textureArrays) {
  58998. var array = this._textureArrays[name];
  58999. for (var index = 0; index < array.length; index++) {
  59000. array[index].dispose();
  59001. }
  59002. }
  59003. }
  59004. this._textures = {};
  59005. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59006. };
  59007. ShaderMaterial.prototype.serialize = function () {
  59008. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59009. serializationObject.customType = "BABYLON.ShaderMaterial";
  59010. serializationObject.options = this._options;
  59011. serializationObject.shaderPath = this._shaderPath;
  59012. var name;
  59013. // Texture
  59014. serializationObject.textures = {};
  59015. for (name in this._textures) {
  59016. serializationObject.textures[name] = this._textures[name].serialize();
  59017. }
  59018. // Texture arrays
  59019. serializationObject.textureArrays = {};
  59020. for (name in this._textureArrays) {
  59021. serializationObject.textureArrays[name] = [];
  59022. var array = this._textureArrays[name];
  59023. for (var index = 0; index < array.length; index++) {
  59024. serializationObject.textureArrays[name].push(array[index].serialize());
  59025. }
  59026. }
  59027. // Float
  59028. serializationObject.floats = {};
  59029. for (name in this._floats) {
  59030. serializationObject.floats[name] = this._floats[name];
  59031. }
  59032. // Float s
  59033. serializationObject.FloatArrays = {};
  59034. for (name in this._floatsArrays) {
  59035. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59036. }
  59037. // Color3
  59038. serializationObject.colors3 = {};
  59039. for (name in this._colors3) {
  59040. serializationObject.colors3[name] = this._colors3[name].asArray();
  59041. }
  59042. // Color3 array
  59043. serializationObject.colors3Arrays = {};
  59044. for (name in this._colors3Arrays) {
  59045. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59046. }
  59047. // Color4
  59048. serializationObject.colors4 = {};
  59049. for (name in this._colors4) {
  59050. serializationObject.colors4[name] = this._colors4[name].asArray();
  59051. }
  59052. // Vector2
  59053. serializationObject.vectors2 = {};
  59054. for (name in this._vectors2) {
  59055. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59056. }
  59057. // Vector3
  59058. serializationObject.vectors3 = {};
  59059. for (name in this._vectors3) {
  59060. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59061. }
  59062. // Vector4
  59063. serializationObject.vectors4 = {};
  59064. for (name in this._vectors4) {
  59065. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59066. }
  59067. // Matrix
  59068. serializationObject.matrices = {};
  59069. for (name in this._matrices) {
  59070. serializationObject.matrices[name] = this._matrices[name].asArray();
  59071. }
  59072. // Matrix 3x3
  59073. serializationObject.matrices3x3 = {};
  59074. for (name in this._matrices3x3) {
  59075. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59076. }
  59077. // Matrix 2x2
  59078. serializationObject.matrices2x2 = {};
  59079. for (name in this._matrices2x2) {
  59080. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59081. }
  59082. // Vector2Array
  59083. serializationObject.vectors2Arrays = {};
  59084. for (name in this._vectors2Arrays) {
  59085. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59086. }
  59087. // Vector3Array
  59088. serializationObject.vectors3Arrays = {};
  59089. for (name in this._vectors3Arrays) {
  59090. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59091. }
  59092. return serializationObject;
  59093. };
  59094. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59095. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59096. var name;
  59097. // Texture
  59098. for (name in source.textures) {
  59099. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59100. }
  59101. // Texture arrays
  59102. for (name in source.textureArrays) {
  59103. var array = source.textureArrays[name];
  59104. var textureArray = new Array();
  59105. for (var index = 0; index < array.length; index++) {
  59106. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59107. }
  59108. material.setTextureArray(name, textureArray);
  59109. }
  59110. // Float
  59111. for (name in source.floats) {
  59112. material.setFloat(name, source.floats[name]);
  59113. }
  59114. // Float s
  59115. for (name in source.floatsArrays) {
  59116. material.setFloats(name, source.floatsArrays[name]);
  59117. }
  59118. // Color3
  59119. for (name in source.colors3) {
  59120. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59121. }
  59122. // Color3 arrays
  59123. for (name in source.colors3Arrays) {
  59124. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59125. if (i % 3 === 0) {
  59126. arr.push([num]);
  59127. }
  59128. else {
  59129. arr[arr.length - 1].push(num);
  59130. }
  59131. return arr;
  59132. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59133. material.setColor3Array(name, colors);
  59134. }
  59135. // Color4
  59136. for (name in source.colors4) {
  59137. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59138. }
  59139. // Vector2
  59140. for (name in source.vectors2) {
  59141. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59142. }
  59143. // Vector3
  59144. for (name in source.vectors3) {
  59145. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59146. }
  59147. // Vector4
  59148. for (name in source.vectors4) {
  59149. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59150. }
  59151. // Matrix
  59152. for (name in source.matrices) {
  59153. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59154. }
  59155. // Matrix 3x3
  59156. for (name in source.matrices3x3) {
  59157. material.setMatrix3x3(name, source.matrices3x3[name]);
  59158. }
  59159. // Matrix 2x2
  59160. for (name in source.matrices2x2) {
  59161. material.setMatrix2x2(name, source.matrices2x2[name]);
  59162. }
  59163. // Vector2Array
  59164. for (name in source.vectors2Arrays) {
  59165. material.setArray2(name, source.vectors2Arrays[name]);
  59166. }
  59167. // Vector3Array
  59168. for (name in source.vectors3Arrays) {
  59169. material.setArray3(name, source.vectors3Arrays[name]);
  59170. }
  59171. return material;
  59172. };
  59173. return ShaderMaterial;
  59174. }(BABYLON.Material));
  59175. BABYLON.ShaderMaterial = ShaderMaterial;
  59176. })(BABYLON || (BABYLON = {}));
  59177. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59178. var BABYLON;
  59179. (function (BABYLON) {
  59180. var GroundMesh = /** @class */ (function (_super) {
  59181. __extends(GroundMesh, _super);
  59182. function GroundMesh(name, scene) {
  59183. var _this = _super.call(this, name, scene) || this;
  59184. _this.generateOctree = false;
  59185. return _this;
  59186. }
  59187. GroundMesh.prototype.getClassName = function () {
  59188. return "GroundMesh";
  59189. };
  59190. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59191. get: function () {
  59192. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59193. },
  59194. enumerable: true,
  59195. configurable: true
  59196. });
  59197. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59198. get: function () {
  59199. return this._subdivisionsX;
  59200. },
  59201. enumerable: true,
  59202. configurable: true
  59203. });
  59204. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59205. get: function () {
  59206. return this._subdivisionsY;
  59207. },
  59208. enumerable: true,
  59209. configurable: true
  59210. });
  59211. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59212. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59213. this._subdivisionsX = chunksCount;
  59214. this._subdivisionsY = chunksCount;
  59215. this.subdivide(chunksCount);
  59216. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59217. };
  59218. /**
  59219. * Returns a height (y) value in the Worl system :
  59220. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59221. * Returns the ground y position if (x, z) are outside the ground surface.
  59222. */
  59223. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59224. var world = this.getWorldMatrix();
  59225. var invMat = BABYLON.Tmp.Matrix[5];
  59226. world.invertToRef(invMat);
  59227. var tmpVect = BABYLON.Tmp.Vector3[8];
  59228. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59229. x = tmpVect.x;
  59230. z = tmpVect.z;
  59231. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59232. return this.position.y;
  59233. }
  59234. if (!this._heightQuads || this._heightQuads.length == 0) {
  59235. this._initHeightQuads();
  59236. this._computeHeightQuads();
  59237. }
  59238. var facet = this._getFacetAt(x, z);
  59239. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59240. // return y in the World system
  59241. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59242. return tmpVect.y;
  59243. };
  59244. /**
  59245. * Returns a normalized vector (Vector3) orthogonal to the ground
  59246. * at the ground coordinates (x, z) expressed in the World system.
  59247. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59248. */
  59249. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59250. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59251. this.getNormalAtCoordinatesToRef(x, z, normal);
  59252. return normal;
  59253. };
  59254. /**
  59255. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59256. * at the ground coordinates (x, z) expressed in the World system.
  59257. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59258. * Returns the GroundMesh.
  59259. */
  59260. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59261. var world = this.getWorldMatrix();
  59262. var tmpMat = BABYLON.Tmp.Matrix[5];
  59263. world.invertToRef(tmpMat);
  59264. var tmpVect = BABYLON.Tmp.Vector3[8];
  59265. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59266. x = tmpVect.x;
  59267. z = tmpVect.z;
  59268. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59269. return this;
  59270. }
  59271. if (!this._heightQuads || this._heightQuads.length == 0) {
  59272. this._initHeightQuads();
  59273. this._computeHeightQuads();
  59274. }
  59275. var facet = this._getFacetAt(x, z);
  59276. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59277. return this;
  59278. };
  59279. /**
  59280. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59281. * if the ground has been updated.
  59282. * This can be used in the render loop.
  59283. * Returns the GroundMesh.
  59284. */
  59285. GroundMesh.prototype.updateCoordinateHeights = function () {
  59286. if (!this._heightQuads || this._heightQuads.length == 0) {
  59287. this._initHeightQuads();
  59288. }
  59289. this._computeHeightQuads();
  59290. return this;
  59291. };
  59292. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59293. GroundMesh.prototype._getFacetAt = function (x, z) {
  59294. // retrieve col and row from x, z coordinates in the ground local system
  59295. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59296. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59297. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59298. var facet;
  59299. if (z < quad.slope.x * x + quad.slope.y) {
  59300. facet = quad.facet1;
  59301. }
  59302. else {
  59303. facet = quad.facet2;
  59304. }
  59305. return facet;
  59306. };
  59307. // Creates and populates the heightMap array with "facet" elements :
  59308. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59309. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59310. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59311. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59312. // Returns the GroundMesh.
  59313. GroundMesh.prototype._initHeightQuads = function () {
  59314. var subdivisionsX = this._subdivisionsX;
  59315. var subdivisionsY = this._subdivisionsY;
  59316. this._heightQuads = new Array();
  59317. for (var row = 0; row < subdivisionsY; row++) {
  59318. for (var col = 0; col < subdivisionsX; col++) {
  59319. 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) };
  59320. this._heightQuads[row * subdivisionsX + col] = quad;
  59321. }
  59322. }
  59323. return this;
  59324. };
  59325. // Compute each quad element values and update the the heightMap array :
  59326. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59327. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59328. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59329. // Returns the GroundMesh.
  59330. GroundMesh.prototype._computeHeightQuads = function () {
  59331. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59332. if (!positions) {
  59333. return this;
  59334. }
  59335. var v1 = BABYLON.Tmp.Vector3[3];
  59336. var v2 = BABYLON.Tmp.Vector3[2];
  59337. var v3 = BABYLON.Tmp.Vector3[1];
  59338. var v4 = BABYLON.Tmp.Vector3[0];
  59339. var v1v2 = BABYLON.Tmp.Vector3[4];
  59340. var v1v3 = BABYLON.Tmp.Vector3[5];
  59341. var v1v4 = BABYLON.Tmp.Vector3[6];
  59342. var norm1 = BABYLON.Tmp.Vector3[7];
  59343. var norm2 = BABYLON.Tmp.Vector3[8];
  59344. var i = 0;
  59345. var j = 0;
  59346. var k = 0;
  59347. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59348. var h = 0;
  59349. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59350. var d2 = 0;
  59351. var subdivisionsX = this._subdivisionsX;
  59352. var subdivisionsY = this._subdivisionsY;
  59353. for (var row = 0; row < subdivisionsY; row++) {
  59354. for (var col = 0; col < subdivisionsX; col++) {
  59355. i = col * 3;
  59356. j = row * (subdivisionsX + 1) * 3;
  59357. k = (row + 1) * (subdivisionsX + 1) * 3;
  59358. v1.x = positions[j + i];
  59359. v1.y = positions[j + i + 1];
  59360. v1.z = positions[j + i + 2];
  59361. v2.x = positions[j + i + 3];
  59362. v2.y = positions[j + i + 4];
  59363. v2.z = positions[j + i + 5];
  59364. v3.x = positions[k + i];
  59365. v3.y = positions[k + i + 1];
  59366. v3.z = positions[k + i + 2];
  59367. v4.x = positions[k + i + 3];
  59368. v4.y = positions[k + i + 4];
  59369. v4.z = positions[k + i + 5];
  59370. // 2D slope V1V4
  59371. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59372. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59373. // facet equations :
  59374. // we compute each facet normal vector
  59375. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59376. // we compute the value d by applying the equation to v1 which belongs to the plane
  59377. // then we store the facet equation in a Vector4
  59378. v2.subtractToRef(v1, v1v2);
  59379. v3.subtractToRef(v1, v1v3);
  59380. v4.subtractToRef(v1, v1v4);
  59381. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59382. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59383. norm1.normalize();
  59384. norm2.normalize();
  59385. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59386. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59387. var quad = this._heightQuads[row * subdivisionsX + col];
  59388. quad.slope.copyFromFloats(cd, h);
  59389. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59390. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59391. }
  59392. }
  59393. return this;
  59394. };
  59395. GroundMesh.prototype.serialize = function (serializationObject) {
  59396. _super.prototype.serialize.call(this, serializationObject);
  59397. serializationObject.subdivisionsX = this._subdivisionsX;
  59398. serializationObject.subdivisionsY = this._subdivisionsY;
  59399. serializationObject.minX = this._minX;
  59400. serializationObject.maxX = this._maxX;
  59401. serializationObject.minZ = this._minZ;
  59402. serializationObject.maxZ = this._maxZ;
  59403. serializationObject.width = this._width;
  59404. serializationObject.height = this._height;
  59405. };
  59406. GroundMesh.Parse = function (parsedMesh, scene) {
  59407. var result = new GroundMesh(parsedMesh.name, scene);
  59408. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59409. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59410. result._minX = parsedMesh.minX;
  59411. result._maxX = parsedMesh.maxX;
  59412. result._minZ = parsedMesh.minZ;
  59413. result._maxZ = parsedMesh.maxZ;
  59414. result._width = parsedMesh.width;
  59415. result._height = parsedMesh.height;
  59416. return result;
  59417. };
  59418. return GroundMesh;
  59419. }(BABYLON.Mesh));
  59420. BABYLON.GroundMesh = GroundMesh;
  59421. })(BABYLON || (BABYLON = {}));
  59422. //# sourceMappingURL=babylon.groundMesh.js.map
  59423. var BABYLON;
  59424. (function (BABYLON) {
  59425. /**
  59426. * Creates an instance based on a source mesh.
  59427. */
  59428. var InstancedMesh = /** @class */ (function (_super) {
  59429. __extends(InstancedMesh, _super);
  59430. function InstancedMesh(name, source) {
  59431. var _this = _super.call(this, name, source.getScene()) || this;
  59432. source.instances.push(_this);
  59433. _this._sourceMesh = source;
  59434. _this.position.copyFrom(source.position);
  59435. _this.rotation.copyFrom(source.rotation);
  59436. _this.scaling.copyFrom(source.scaling);
  59437. if (source.rotationQuaternion) {
  59438. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59439. }
  59440. _this.infiniteDistance = source.infiniteDistance;
  59441. _this.setPivotMatrix(source.getPivotMatrix());
  59442. _this.refreshBoundingInfo();
  59443. _this._syncSubMeshes();
  59444. return _this;
  59445. }
  59446. /**
  59447. * Returns the string "InstancedMesh".
  59448. */
  59449. InstancedMesh.prototype.getClassName = function () {
  59450. return "InstancedMesh";
  59451. };
  59452. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59453. // Methods
  59454. get: function () {
  59455. return this._sourceMesh.receiveShadows;
  59456. },
  59457. enumerable: true,
  59458. configurable: true
  59459. });
  59460. Object.defineProperty(InstancedMesh.prototype, "material", {
  59461. get: function () {
  59462. return this._sourceMesh.material;
  59463. },
  59464. enumerable: true,
  59465. configurable: true
  59466. });
  59467. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59468. get: function () {
  59469. return this._sourceMesh.visibility;
  59470. },
  59471. enumerable: true,
  59472. configurable: true
  59473. });
  59474. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59475. get: function () {
  59476. return this._sourceMesh.skeleton;
  59477. },
  59478. enumerable: true,
  59479. configurable: true
  59480. });
  59481. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59482. get: function () {
  59483. return this._sourceMesh.renderingGroupId;
  59484. },
  59485. set: function (value) {
  59486. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59487. return;
  59488. }
  59489. //no-op with warning
  59490. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59491. },
  59492. enumerable: true,
  59493. configurable: true
  59494. });
  59495. /**
  59496. * Returns the total number of vertices (integer).
  59497. */
  59498. InstancedMesh.prototype.getTotalVertices = function () {
  59499. return this._sourceMesh.getTotalVertices();
  59500. };
  59501. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59502. get: function () {
  59503. return this._sourceMesh;
  59504. },
  59505. enumerable: true,
  59506. configurable: true
  59507. });
  59508. /**
  59509. * Is this node ready to be used/rendered
  59510. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59511. * @return {boolean} is it ready
  59512. */
  59513. InstancedMesh.prototype.isReady = function (completeCheck) {
  59514. if (completeCheck === void 0) { completeCheck = false; }
  59515. return this._sourceMesh.isReady(completeCheck, true);
  59516. };
  59517. /**
  59518. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59519. */
  59520. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59521. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59522. };
  59523. /**
  59524. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59525. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59526. * The `data` are either a numeric array either a Float32Array.
  59527. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59528. * 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).
  59529. * Note that a new underlying VertexBuffer object is created each call.
  59530. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59531. *
  59532. * Possible `kind` values :
  59533. * - BABYLON.VertexBuffer.PositionKind
  59534. * - BABYLON.VertexBuffer.UVKind
  59535. * - BABYLON.VertexBuffer.UV2Kind
  59536. * - BABYLON.VertexBuffer.UV3Kind
  59537. * - BABYLON.VertexBuffer.UV4Kind
  59538. * - BABYLON.VertexBuffer.UV5Kind
  59539. * - BABYLON.VertexBuffer.UV6Kind
  59540. * - BABYLON.VertexBuffer.ColorKind
  59541. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59542. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59543. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59544. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59545. *
  59546. * Returns the Mesh.
  59547. */
  59548. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  59549. if (this.sourceMesh) {
  59550. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  59551. }
  59552. return this.sourceMesh;
  59553. };
  59554. /**
  59555. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  59556. * If the mesh has no geometry, it is simply returned as it is.
  59557. * The `data` are either a numeric array either a Float32Array.
  59558. * No new underlying VertexBuffer object is created.
  59559. * 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.
  59560. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  59561. *
  59562. * Possible `kind` values :
  59563. * - BABYLON.VertexBuffer.PositionKind
  59564. * - BABYLON.VertexBuffer.UVKind
  59565. * - BABYLON.VertexBuffer.UV2Kind
  59566. * - BABYLON.VertexBuffer.UV3Kind
  59567. * - BABYLON.VertexBuffer.UV4Kind
  59568. * - BABYLON.VertexBuffer.UV5Kind
  59569. * - BABYLON.VertexBuffer.UV6Kind
  59570. * - BABYLON.VertexBuffer.ColorKind
  59571. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59572. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59573. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59574. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59575. *
  59576. * Returns the Mesh.
  59577. */
  59578. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  59579. if (this.sourceMesh) {
  59580. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  59581. }
  59582. return this.sourceMesh;
  59583. };
  59584. /**
  59585. * Sets the mesh indices.
  59586. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  59587. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  59588. * This method creates a new index buffer each call.
  59589. * Returns the Mesh.
  59590. */
  59591. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  59592. if (totalVertices === void 0) { totalVertices = null; }
  59593. if (this.sourceMesh) {
  59594. this.sourceMesh.setIndices(indices, totalVertices);
  59595. }
  59596. return this.sourceMesh;
  59597. };
  59598. /**
  59599. * Boolean : True if the mesh owns the requested kind of data.
  59600. */
  59601. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  59602. return this._sourceMesh.isVerticesDataPresent(kind);
  59603. };
  59604. /**
  59605. * Returns an array of indices (IndicesArray).
  59606. */
  59607. InstancedMesh.prototype.getIndices = function () {
  59608. return this._sourceMesh.getIndices();
  59609. };
  59610. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  59611. get: function () {
  59612. return this._sourceMesh._positions;
  59613. },
  59614. enumerable: true,
  59615. configurable: true
  59616. });
  59617. /**
  59618. * Sets a new updated BoundingInfo to the mesh.
  59619. * Returns the mesh.
  59620. */
  59621. InstancedMesh.prototype.refreshBoundingInfo = function () {
  59622. var meshBB = this._sourceMesh.getBoundingInfo();
  59623. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  59624. this._updateBoundingInfo();
  59625. return this;
  59626. };
  59627. /** @hidden */
  59628. InstancedMesh.prototype._preActivate = function () {
  59629. if (this._currentLOD) {
  59630. this._currentLOD._preActivate();
  59631. }
  59632. return this;
  59633. };
  59634. /** @hidden */
  59635. InstancedMesh.prototype._activate = function (renderId) {
  59636. if (this._currentLOD) {
  59637. this._currentLOD._registerInstanceForRenderId(this, renderId);
  59638. }
  59639. return this;
  59640. };
  59641. /**
  59642. * Returns the current associated LOD AbstractMesh.
  59643. */
  59644. InstancedMesh.prototype.getLOD = function (camera) {
  59645. if (!camera) {
  59646. return this;
  59647. }
  59648. var boundingInfo = this.getBoundingInfo();
  59649. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  59650. if (this._currentLOD === this.sourceMesh) {
  59651. return this;
  59652. }
  59653. return this._currentLOD;
  59654. };
  59655. /** @hidden */
  59656. InstancedMesh.prototype._syncSubMeshes = function () {
  59657. this.releaseSubMeshes();
  59658. if (this._sourceMesh.subMeshes) {
  59659. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  59660. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  59661. }
  59662. }
  59663. return this;
  59664. };
  59665. /** @hidden */
  59666. InstancedMesh.prototype._generatePointsArray = function () {
  59667. return this._sourceMesh._generatePointsArray();
  59668. };
  59669. /**
  59670. * Creates a new InstancedMesh from the current mesh.
  59671. * - name (string) : the cloned mesh name
  59672. * - newParent (optional Node) : the optional Node to parent the clone to.
  59673. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  59674. *
  59675. * Returns the clone.
  59676. */
  59677. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59678. var result = this._sourceMesh.createInstance(name);
  59679. // Deep copy
  59680. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  59681. // Bounding info
  59682. this.refreshBoundingInfo();
  59683. // Parent
  59684. if (newParent) {
  59685. result.parent = newParent;
  59686. }
  59687. if (!doNotCloneChildren) {
  59688. // Children
  59689. for (var index = 0; index < this.getScene().meshes.length; index++) {
  59690. var mesh = this.getScene().meshes[index];
  59691. if (mesh.parent === this) {
  59692. mesh.clone(mesh.name, result);
  59693. }
  59694. }
  59695. }
  59696. result.computeWorldMatrix(true);
  59697. return result;
  59698. };
  59699. /**
  59700. * Disposes the InstancedMesh.
  59701. * Returns nothing.
  59702. */
  59703. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  59704. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  59705. // Remove from mesh
  59706. var index = this._sourceMesh.instances.indexOf(this);
  59707. this._sourceMesh.instances.splice(index, 1);
  59708. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  59709. };
  59710. return InstancedMesh;
  59711. }(BABYLON.AbstractMesh));
  59712. BABYLON.InstancedMesh = InstancedMesh;
  59713. })(BABYLON || (BABYLON = {}));
  59714. //# sourceMappingURL=babylon.instancedMesh.js.map
  59715. var BABYLON;
  59716. (function (BABYLON) {
  59717. var LinesMesh = /** @class */ (function (_super) {
  59718. __extends(LinesMesh, _super);
  59719. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  59720. if (scene === void 0) { scene = null; }
  59721. if (parent === void 0) { parent = null; }
  59722. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  59723. _this.useVertexColor = useVertexColor;
  59724. _this.useVertexAlpha = useVertexAlpha;
  59725. _this.color = new BABYLON.Color3(1, 1, 1);
  59726. _this.alpha = 1;
  59727. if (source) {
  59728. _this.color = source.color.clone();
  59729. _this.alpha = source.alpha;
  59730. _this.useVertexColor = source.useVertexColor;
  59731. _this.useVertexAlpha = source.useVertexAlpha;
  59732. }
  59733. _this._intersectionThreshold = 0.1;
  59734. var defines = [];
  59735. var options = {
  59736. attributes: [BABYLON.VertexBuffer.PositionKind],
  59737. uniforms: ["world", "viewProjection"],
  59738. needAlphaBlending: true,
  59739. defines: defines
  59740. };
  59741. if (useVertexAlpha === false) {
  59742. options.needAlphaBlending = false;
  59743. }
  59744. if (!useVertexColor) {
  59745. options.uniforms.push("color");
  59746. }
  59747. else {
  59748. options.defines.push("#define VERTEXCOLOR");
  59749. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  59750. }
  59751. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  59752. return _this;
  59753. }
  59754. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  59755. /**
  59756. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59757. * This margin is expressed in world space coordinates, so its value may vary.
  59758. * Default value is 0.1
  59759. * @returns the intersection Threshold value.
  59760. */
  59761. get: function () {
  59762. return this._intersectionThreshold;
  59763. },
  59764. /**
  59765. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59766. * This margin is expressed in world space coordinates, so its value may vary.
  59767. * @param value the new threshold to apply
  59768. */
  59769. set: function (value) {
  59770. if (this._intersectionThreshold === value) {
  59771. return;
  59772. }
  59773. this._intersectionThreshold = value;
  59774. if (this.geometry) {
  59775. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  59776. }
  59777. },
  59778. enumerable: true,
  59779. configurable: true
  59780. });
  59781. /**
  59782. * Returns the string "LineMesh"
  59783. */
  59784. LinesMesh.prototype.getClassName = function () {
  59785. return "LinesMesh";
  59786. };
  59787. Object.defineProperty(LinesMesh.prototype, "material", {
  59788. /**
  59789. * @hidden
  59790. */
  59791. get: function () {
  59792. return this._colorShader;
  59793. },
  59794. /**
  59795. * @hidden
  59796. */
  59797. set: function (value) {
  59798. // Do nothing
  59799. },
  59800. enumerable: true,
  59801. configurable: true
  59802. });
  59803. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  59804. /**
  59805. * @hidden
  59806. */
  59807. get: function () {
  59808. return false;
  59809. },
  59810. enumerable: true,
  59811. configurable: true
  59812. });
  59813. LinesMesh.prototype.createInstance = function (name) {
  59814. throw new Error("LinesMeshes do not support createInstance.");
  59815. };
  59816. /** @hidden */
  59817. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  59818. if (!this._geometry) {
  59819. return this;
  59820. }
  59821. // VBOs
  59822. this._geometry._bind(this._colorShader.getEffect());
  59823. // Color
  59824. if (!this.useVertexColor) {
  59825. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  59826. }
  59827. return this;
  59828. };
  59829. /** @hidden */
  59830. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  59831. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  59832. return this;
  59833. }
  59834. var engine = this.getScene().getEngine();
  59835. // Draw order
  59836. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  59837. return this;
  59838. };
  59839. LinesMesh.prototype.dispose = function (doNotRecurse) {
  59840. this._colorShader.dispose();
  59841. _super.prototype.dispose.call(this, doNotRecurse);
  59842. };
  59843. /**
  59844. * Returns a new LineMesh object cloned from the current one.
  59845. */
  59846. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59847. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  59848. };
  59849. /**
  59850. * Enables the edge rendering mode on the mesh.
  59851. * This mode makes the mesh edges visible
  59852. * @param epsilon defines the maximal distance between two angles to detect a face
  59853. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  59854. * @returns the currentAbstractMesh
  59855. * @see https://www.babylonjs-playground.com/#19O9TU#0
  59856. */
  59857. LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  59858. if (epsilon === void 0) { epsilon = 0.95; }
  59859. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  59860. this.disableEdgesRendering();
  59861. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  59862. return this;
  59863. };
  59864. return LinesMesh;
  59865. }(BABYLON.Mesh));
  59866. BABYLON.LinesMesh = LinesMesh;
  59867. })(BABYLON || (BABYLON = {}));
  59868. //# sourceMappingURL=babylon.linesMesh.js.map
  59869. var BABYLON;
  59870. (function (BABYLON) {
  59871. /**
  59872. * This class implement a typical dictionary using a string as key and the generic type T as value.
  59873. * The underlying implementation relies on an associative array to ensure the best performances.
  59874. * The value can be anything including 'null' but except 'undefined'
  59875. */
  59876. var StringDictionary = /** @class */ (function () {
  59877. function StringDictionary() {
  59878. this._count = 0;
  59879. this._data = {};
  59880. }
  59881. /**
  59882. * This will clear this dictionary and copy the content from the 'source' one.
  59883. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  59884. * @param source the dictionary to take the content from and copy to this dictionary
  59885. */
  59886. StringDictionary.prototype.copyFrom = function (source) {
  59887. var _this = this;
  59888. this.clear();
  59889. source.forEach(function (t, v) { return _this.add(t, v); });
  59890. };
  59891. /**
  59892. * Get a value based from its key
  59893. * @param key the given key to get the matching value from
  59894. * @return the value if found, otherwise undefined is returned
  59895. */
  59896. StringDictionary.prototype.get = function (key) {
  59897. var val = this._data[key];
  59898. if (val !== undefined) {
  59899. return val;
  59900. }
  59901. return undefined;
  59902. };
  59903. /**
  59904. * Get a value from its key or add it if it doesn't exist.
  59905. * This method will ensure you that a given key/data will be present in the dictionary.
  59906. * @param key the given key to get the matching value from
  59907. * @param factory the factory that will create the value if the key is not present in the dictionary.
  59908. * The factory will only be invoked if there's no data for the given key.
  59909. * @return the value corresponding to the key.
  59910. */
  59911. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  59912. var val = this.get(key);
  59913. if (val !== undefined) {
  59914. return val;
  59915. }
  59916. val = factory(key);
  59917. if (val) {
  59918. this.add(key, val);
  59919. }
  59920. return val;
  59921. };
  59922. /**
  59923. * Get a value from its key if present in the dictionary otherwise add it
  59924. * @param key the key to get the value from
  59925. * @param val if there's no such key/value pair in the dictionary add it with this value
  59926. * @return the value corresponding to the key
  59927. */
  59928. StringDictionary.prototype.getOrAdd = function (key, val) {
  59929. var curVal = this.get(key);
  59930. if (curVal !== undefined) {
  59931. return curVal;
  59932. }
  59933. this.add(key, val);
  59934. return val;
  59935. };
  59936. /**
  59937. * Check if there's a given key in the dictionary
  59938. * @param key the key to check for
  59939. * @return true if the key is present, false otherwise
  59940. */
  59941. StringDictionary.prototype.contains = function (key) {
  59942. return this._data[key] !== undefined;
  59943. };
  59944. /**
  59945. * Add a new key and its corresponding value
  59946. * @param key the key to add
  59947. * @param value the value corresponding to the key
  59948. * @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
  59949. */
  59950. StringDictionary.prototype.add = function (key, value) {
  59951. if (this._data[key] !== undefined) {
  59952. return false;
  59953. }
  59954. this._data[key] = value;
  59955. ++this._count;
  59956. return true;
  59957. };
  59958. StringDictionary.prototype.set = function (key, value) {
  59959. if (this._data[key] === undefined) {
  59960. return false;
  59961. }
  59962. this._data[key] = value;
  59963. return true;
  59964. };
  59965. /**
  59966. * Get the element of the given key and remove it from the dictionary
  59967. * @param key
  59968. */
  59969. StringDictionary.prototype.getAndRemove = function (key) {
  59970. var val = this.get(key);
  59971. if (val !== undefined) {
  59972. delete this._data[key];
  59973. --this._count;
  59974. return val;
  59975. }
  59976. return null;
  59977. };
  59978. /**
  59979. * Remove a key/value from the dictionary.
  59980. * @param key the key to remove
  59981. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  59982. */
  59983. StringDictionary.prototype.remove = function (key) {
  59984. if (this.contains(key)) {
  59985. delete this._data[key];
  59986. --this._count;
  59987. return true;
  59988. }
  59989. return false;
  59990. };
  59991. /**
  59992. * Clear the whole content of the dictionary
  59993. */
  59994. StringDictionary.prototype.clear = function () {
  59995. this._data = {};
  59996. this._count = 0;
  59997. };
  59998. Object.defineProperty(StringDictionary.prototype, "count", {
  59999. get: function () {
  60000. return this._count;
  60001. },
  60002. enumerable: true,
  60003. configurable: true
  60004. });
  60005. /**
  60006. * Execute a callback on each key/val of the dictionary.
  60007. * Note that you can remove any element in this dictionary in the callback implementation
  60008. * @param callback the callback to execute on a given key/value pair
  60009. */
  60010. StringDictionary.prototype.forEach = function (callback) {
  60011. for (var cur in this._data) {
  60012. var val = this._data[cur];
  60013. callback(cur, val);
  60014. }
  60015. };
  60016. /**
  60017. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  60018. * If the callback returns null or undefined the method will iterate to the next key/value pair
  60019. * Note that you can remove any element in this dictionary in the callback implementation
  60020. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  60021. */
  60022. StringDictionary.prototype.first = function (callback) {
  60023. for (var cur in this._data) {
  60024. var val = this._data[cur];
  60025. var res = callback(cur, val);
  60026. if (res) {
  60027. return res;
  60028. }
  60029. }
  60030. return null;
  60031. };
  60032. return StringDictionary;
  60033. }());
  60034. BABYLON.StringDictionary = StringDictionary;
  60035. })(BABYLON || (BABYLON = {}));
  60036. //# sourceMappingURL=babylon.stringDictionary.js.map
  60037. var BABYLON;
  60038. (function (BABYLON) {
  60039. var Debug;
  60040. (function (Debug) {
  60041. /**
  60042. * Class used to render a debug view of a given skeleton
  60043. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  60044. */
  60045. var SkeletonViewer = /** @class */ (function () {
  60046. /**
  60047. * Creates a new SkeletonViewer
  60048. * @param skeleton defines the skeleton to render
  60049. * @param mesh defines the mesh attached to the skeleton
  60050. * @param scene defines the hosting scene
  60051. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  60052. * @param renderingGroupId defines the rendering group id to use with the viewer
  60053. */
  60054. function SkeletonViewer(
  60055. /** defines the skeleton to render */
  60056. skeleton,
  60057. /** defines the mesh attached to the skeleton */
  60058. mesh, scene,
  60059. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  60060. autoUpdateBonesMatrices,
  60061. /** defines the rendering group id to use with the viewer */
  60062. renderingGroupId) {
  60063. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  60064. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  60065. this.skeleton = skeleton;
  60066. this.mesh = mesh;
  60067. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  60068. this.renderingGroupId = renderingGroupId;
  60069. /** Gets or sets the color used to render the skeleton */
  60070. this.color = BABYLON.Color3.White();
  60071. this._debugLines = new Array();
  60072. this._isEnabled = false;
  60073. this._scene = scene;
  60074. this.update();
  60075. this._renderFunction = this.update.bind(this);
  60076. }
  60077. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  60078. get: function () {
  60079. return this._isEnabled;
  60080. },
  60081. /** Gets or sets a boolean indicating if the viewer is enabled */
  60082. set: function (value) {
  60083. if (this._isEnabled === value) {
  60084. return;
  60085. }
  60086. this._isEnabled = value;
  60087. if (value) {
  60088. this._scene.registerBeforeRender(this._renderFunction);
  60089. }
  60090. else {
  60091. this._scene.unregisterBeforeRender(this._renderFunction);
  60092. }
  60093. },
  60094. enumerable: true,
  60095. configurable: true
  60096. });
  60097. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  60098. if (x === void 0) { x = 0; }
  60099. if (y === void 0) { y = 0; }
  60100. if (z === void 0) { z = 0; }
  60101. var tmat = BABYLON.Tmp.Matrix[0];
  60102. var parentBone = bone.getParent();
  60103. tmat.copyFrom(bone.getLocalMatrix());
  60104. if (x !== 0 || y !== 0 || z !== 0) {
  60105. var tmat2 = BABYLON.Tmp.Matrix[1];
  60106. BABYLON.Matrix.IdentityToRef(tmat2);
  60107. tmat2.m[12] = x;
  60108. tmat2.m[13] = y;
  60109. tmat2.m[14] = z;
  60110. tmat2.multiplyToRef(tmat, tmat);
  60111. }
  60112. if (parentBone) {
  60113. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  60114. }
  60115. tmat.multiplyToRef(meshMat, tmat);
  60116. position.x = tmat.m[12];
  60117. position.y = tmat.m[13];
  60118. position.z = tmat.m[14];
  60119. };
  60120. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  60121. var len = bones.length;
  60122. var meshPos = this.mesh.position;
  60123. for (var i = 0; i < len; i++) {
  60124. var bone = bones[i];
  60125. var points = this._debugLines[i];
  60126. if (!points) {
  60127. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60128. this._debugLines[i] = points;
  60129. }
  60130. this._getBonePosition(points[0], bone, meshMat);
  60131. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  60132. points[0].subtractInPlace(meshPos);
  60133. points[1].subtractInPlace(meshPos);
  60134. }
  60135. };
  60136. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  60137. var len = bones.length;
  60138. var boneNum = 0;
  60139. var meshPos = this.mesh.position;
  60140. for (var i = len - 1; i >= 0; i--) {
  60141. var childBone = bones[i];
  60142. var parentBone = childBone.getParent();
  60143. if (!parentBone) {
  60144. continue;
  60145. }
  60146. var points = this._debugLines[boneNum];
  60147. if (!points) {
  60148. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60149. this._debugLines[boneNum] = points;
  60150. }
  60151. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  60152. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  60153. points[0].subtractInPlace(meshPos);
  60154. points[1].subtractInPlace(meshPos);
  60155. boneNum++;
  60156. }
  60157. };
  60158. /** Update the viewer to sync with current skeleton state */
  60159. SkeletonViewer.prototype.update = function () {
  60160. if (this.autoUpdateBonesMatrices) {
  60161. this.skeleton.computeAbsoluteTransforms();
  60162. }
  60163. if (this.skeleton.bones[0].length === undefined) {
  60164. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60165. }
  60166. else {
  60167. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60168. }
  60169. if (!this._debugMesh) {
  60170. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  60171. this._debugMesh.renderingGroupId = this.renderingGroupId;
  60172. }
  60173. else {
  60174. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  60175. }
  60176. this._debugMesh.position.copyFrom(this.mesh.position);
  60177. this._debugMesh.color = this.color;
  60178. };
  60179. /** Release associated resources */
  60180. SkeletonViewer.prototype.dispose = function () {
  60181. if (this._debugMesh) {
  60182. this.isEnabled = false;
  60183. this._debugMesh.dispose();
  60184. this._debugMesh = null;
  60185. }
  60186. };
  60187. return SkeletonViewer;
  60188. }());
  60189. Debug.SkeletonViewer = SkeletonViewer;
  60190. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60191. })(BABYLON || (BABYLON = {}));
  60192. //# sourceMappingURL=babylon.skeletonViewer.js.map
  60193. /**
  60194. * Module Debug contains the (visual) components to debug a scene correctly
  60195. */
  60196. var BABYLON;
  60197. (function (BABYLON) {
  60198. var Debug;
  60199. (function (Debug) {
  60200. /**
  60201. * The Axes viewer will show 3 axes in a specific point in space
  60202. */
  60203. var AxesViewer = /** @class */ (function () {
  60204. /**
  60205. * Creates a new AxesViewer
  60206. * @param scene defines the hosting scene
  60207. * @param scaleLines defines a number used to scale line length (1 by default)
  60208. */
  60209. function AxesViewer(scene, scaleLines) {
  60210. if (scaleLines === void 0) { scaleLines = 1; }
  60211. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60212. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60213. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60214. /**
  60215. * Gets or sets a number used to scale line length
  60216. */
  60217. this.scaleLines = 1;
  60218. this.scaleLines = scaleLines;
  60219. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  60220. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  60221. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  60222. this._xmesh.renderingGroupId = 2;
  60223. this._ymesh.renderingGroupId = 2;
  60224. this._zmesh.renderingGroupId = 2;
  60225. this._xmesh.material.checkReadyOnlyOnce = true;
  60226. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  60227. this._ymesh.material.checkReadyOnlyOnce = true;
  60228. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  60229. this._zmesh.material.checkReadyOnlyOnce = true;
  60230. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  60231. this.scene = scene;
  60232. }
  60233. /**
  60234. * Force the viewer to update
  60235. * @param position defines the position of the viewer
  60236. * @param xaxis defines the x axis of the viewer
  60237. * @param yaxis defines the y axis of the viewer
  60238. * @param zaxis defines the z axis of the viewer
  60239. */
  60240. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  60241. var scaleLines = this.scaleLines;
  60242. if (this._xmesh) {
  60243. this._xmesh.position.copyFrom(position);
  60244. }
  60245. if (this._ymesh) {
  60246. this._ymesh.position.copyFrom(position);
  60247. }
  60248. if (this._zmesh) {
  60249. this._zmesh.position.copyFrom(position);
  60250. }
  60251. var point2 = this._xline[1];
  60252. point2.x = xaxis.x * scaleLines;
  60253. point2.y = xaxis.y * scaleLines;
  60254. point2.z = xaxis.z * scaleLines;
  60255. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  60256. point2 = this._yline[1];
  60257. point2.x = yaxis.x * scaleLines;
  60258. point2.y = yaxis.y * scaleLines;
  60259. point2.z = yaxis.z * scaleLines;
  60260. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  60261. point2 = this._zline[1];
  60262. point2.x = zaxis.x * scaleLines;
  60263. point2.y = zaxis.y * scaleLines;
  60264. point2.z = zaxis.z * scaleLines;
  60265. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  60266. };
  60267. /** Releases resources */
  60268. AxesViewer.prototype.dispose = function () {
  60269. if (this._xmesh) {
  60270. this._xmesh.dispose();
  60271. }
  60272. if (this._ymesh) {
  60273. this._ymesh.dispose();
  60274. }
  60275. if (this._zmesh) {
  60276. this._zmesh.dispose();
  60277. }
  60278. this._xmesh = null;
  60279. this._ymesh = null;
  60280. this._zmesh = null;
  60281. this.scene = null;
  60282. };
  60283. return AxesViewer;
  60284. }());
  60285. Debug.AxesViewer = AxesViewer;
  60286. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60287. })(BABYLON || (BABYLON = {}));
  60288. //# sourceMappingURL=babylon.axesViewer.js.map
  60289. var BABYLON;
  60290. (function (BABYLON) {
  60291. var Debug;
  60292. (function (Debug) {
  60293. /**
  60294. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  60295. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  60296. */
  60297. var BoneAxesViewer = /** @class */ (function (_super) {
  60298. __extends(BoneAxesViewer, _super);
  60299. /**
  60300. * Creates a new BoneAxesViewer
  60301. * @param scene defines the hosting scene
  60302. * @param bone defines the target bone
  60303. * @param mesh defines the target mesh
  60304. * @param scaleLines defines a scaling factor for line length (1 by default)
  60305. */
  60306. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  60307. if (scaleLines === void 0) { scaleLines = 1; }
  60308. var _this = _super.call(this, scene, scaleLines) || this;
  60309. /** Gets current position */
  60310. _this.pos = BABYLON.Vector3.Zero();
  60311. /** Gets direction of X axis */
  60312. _this.xaxis = BABYLON.Vector3.Zero();
  60313. /** Gets direction of Y axis */
  60314. _this.yaxis = BABYLON.Vector3.Zero();
  60315. /** Gets direction of Z axis */
  60316. _this.zaxis = BABYLON.Vector3.Zero();
  60317. _this.mesh = mesh;
  60318. _this.bone = bone;
  60319. return _this;
  60320. }
  60321. /**
  60322. * Force the viewer to update
  60323. */
  60324. BoneAxesViewer.prototype.update = function () {
  60325. if (!this.mesh || !this.bone) {
  60326. return;
  60327. }
  60328. var bone = this.bone;
  60329. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  60330. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  60331. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  60332. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  60333. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  60334. };
  60335. /** Releases resources */
  60336. BoneAxesViewer.prototype.dispose = function () {
  60337. if (this.mesh) {
  60338. this.mesh = null;
  60339. this.bone = null;
  60340. _super.prototype.dispose.call(this);
  60341. }
  60342. };
  60343. return BoneAxesViewer;
  60344. }(Debug.AxesViewer));
  60345. Debug.BoneAxesViewer = BoneAxesViewer;
  60346. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60347. })(BABYLON || (BABYLON = {}));
  60348. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  60349. var BABYLON;
  60350. (function (BABYLON) {
  60351. var RayHelper = /** @class */ (function () {
  60352. function RayHelper(ray) {
  60353. this.ray = ray;
  60354. }
  60355. RayHelper.CreateAndShow = function (ray, scene, color) {
  60356. var helper = new RayHelper(ray);
  60357. helper.show(scene, color);
  60358. return helper;
  60359. };
  60360. RayHelper.prototype.show = function (scene, color) {
  60361. if (!this._renderFunction && this.ray) {
  60362. var ray = this.ray;
  60363. this._renderFunction = this._render.bind(this);
  60364. this._scene = scene;
  60365. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  60366. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  60367. if (this._renderFunction) {
  60368. this._scene.registerBeforeRender(this._renderFunction);
  60369. }
  60370. }
  60371. if (color && this._renderLine) {
  60372. this._renderLine.color.copyFrom(color);
  60373. }
  60374. };
  60375. RayHelper.prototype.hide = function () {
  60376. if (this._renderFunction && this._scene) {
  60377. this._scene.unregisterBeforeRender(this._renderFunction);
  60378. this._scene = null;
  60379. this._renderFunction = null;
  60380. if (this._renderLine) {
  60381. this._renderLine.dispose();
  60382. this._renderLine = null;
  60383. }
  60384. this._renderPoints = [];
  60385. }
  60386. };
  60387. RayHelper.prototype._render = function () {
  60388. var ray = this.ray;
  60389. if (!ray) {
  60390. return;
  60391. }
  60392. var point = this._renderPoints[1];
  60393. var len = Math.min(ray.length, 1000000);
  60394. point.copyFrom(ray.direction);
  60395. point.scaleInPlace(len);
  60396. point.addInPlace(ray.origin);
  60397. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  60398. };
  60399. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  60400. this._attachedToMesh = mesh;
  60401. var ray = this.ray;
  60402. if (!ray) {
  60403. return;
  60404. }
  60405. if (!ray.direction) {
  60406. ray.direction = BABYLON.Vector3.Zero();
  60407. }
  60408. if (!ray.origin) {
  60409. ray.origin = BABYLON.Vector3.Zero();
  60410. }
  60411. if (length) {
  60412. ray.length = length;
  60413. }
  60414. if (!meshSpaceOrigin) {
  60415. meshSpaceOrigin = BABYLON.Vector3.Zero();
  60416. }
  60417. if (!meshSpaceDirection) {
  60418. // -1 so that this will work with Mesh.lookAt
  60419. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  60420. }
  60421. if (!this._meshSpaceDirection) {
  60422. this._meshSpaceDirection = meshSpaceDirection.clone();
  60423. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  60424. }
  60425. else {
  60426. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  60427. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  60428. }
  60429. if (!this._updateToMeshFunction) {
  60430. this._updateToMeshFunction = this._updateToMesh.bind(this);
  60431. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  60432. }
  60433. this._updateToMesh();
  60434. };
  60435. RayHelper.prototype.detachFromMesh = function () {
  60436. if (this._attachedToMesh) {
  60437. if (this._updateToMeshFunction) {
  60438. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  60439. }
  60440. this._attachedToMesh = null;
  60441. this._updateToMeshFunction = null;
  60442. }
  60443. };
  60444. RayHelper.prototype._updateToMesh = function () {
  60445. var ray = this.ray;
  60446. if (!this._attachedToMesh || !ray) {
  60447. return;
  60448. }
  60449. if (this._attachedToMesh._isDisposed) {
  60450. this.detachFromMesh();
  60451. return;
  60452. }
  60453. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  60454. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  60455. };
  60456. RayHelper.prototype.dispose = function () {
  60457. this.hide();
  60458. this.detachFromMesh();
  60459. this.ray = null;
  60460. };
  60461. return RayHelper;
  60462. }());
  60463. BABYLON.RayHelper = RayHelper;
  60464. })(BABYLON || (BABYLON = {}));
  60465. //# sourceMappingURL=babylon.rayHelper.js.map
  60466. var BABYLON;
  60467. (function (BABYLON) {
  60468. // load the inspector using require, if not present in the global namespace.
  60469. var DebugLayer = /** @class */ (function () {
  60470. function DebugLayer(scene) {
  60471. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  60472. this.onPropertyChangedObservable = new BABYLON.Observable();
  60473. this._scene = scene;
  60474. }
  60475. /** Creates the inspector window. */
  60476. DebugLayer.prototype._createInspector = function (config) {
  60477. if (config === void 0) { config = {}; }
  60478. var popup = config.popup || false;
  60479. var initialTab = config.initialTab || 0;
  60480. var parentElement = config.parentElement || null;
  60481. if (!this._inspector) {
  60482. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  60483. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  60484. } // else nothing to do as instance is already created
  60485. };
  60486. DebugLayer.prototype.isVisible = function () {
  60487. if (!this._inspector) {
  60488. return false;
  60489. }
  60490. return true;
  60491. };
  60492. DebugLayer.prototype.hide = function () {
  60493. if (this._inspector) {
  60494. try {
  60495. this._inspector.dispose();
  60496. }
  60497. catch (e) {
  60498. // If the inspector has been removed directly from the inspector tool
  60499. }
  60500. this.onPropertyChangedObservable.clear();
  60501. this._inspector = null;
  60502. }
  60503. };
  60504. /**
  60505. *
  60506. * Launch the debugLayer.
  60507. *
  60508. * initialTab:
  60509. * | Value | Tab Name |
  60510. * | --- | --- |
  60511. * | 0 | Scene |
  60512. * | 1 | Console |
  60513. * | 2 | Stats |
  60514. * | 3 | Textures |
  60515. * | 4 | Mesh |
  60516. * | 5 | Light |
  60517. * | 6 | Material |
  60518. * | 7 | GLTF |
  60519. * | 8 | GUI |
  60520. * | 9 | Physics |
  60521. * | 10 | Camera |
  60522. * | 11 | Audio |
  60523. *
  60524. */
  60525. DebugLayer.prototype.show = function (config) {
  60526. if (config === void 0) { config = {}; }
  60527. if (typeof this.BJSINSPECTOR == 'undefined') {
  60528. // Load inspector and add it to the DOM
  60529. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  60530. }
  60531. else {
  60532. // Otherwise creates the inspector
  60533. this._createInspector(config);
  60534. }
  60535. };
  60536. /**
  60537. * Gets the active tab
  60538. * @return the index of the active tab or -1 if the inspector is hidden
  60539. */
  60540. DebugLayer.prototype.getActiveTab = function () {
  60541. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  60542. };
  60543. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  60544. return DebugLayer;
  60545. }());
  60546. BABYLON.DebugLayer = DebugLayer;
  60547. })(BABYLON || (BABYLON = {}));
  60548. //# sourceMappingURL=babylon.debugLayer.js.map
  60549. var BABYLON;
  60550. (function (BABYLON) {
  60551. var Debug;
  60552. (function (Debug) {
  60553. /**
  60554. * Used to show the physics impostor around the specific mesh
  60555. */
  60556. var PhysicsViewer = /** @class */ (function () {
  60557. /**
  60558. * Creates a new PhysicsViewer
  60559. * @param scene defines the hosting scene
  60560. */
  60561. function PhysicsViewer(scene) {
  60562. /** @hidden */
  60563. this._impostors = [];
  60564. /** @hidden */
  60565. this._meshes = [];
  60566. /** @hidden */
  60567. this._numMeshes = 0;
  60568. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60569. var physicEngine = this._scene.getPhysicsEngine();
  60570. if (physicEngine) {
  60571. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  60572. }
  60573. }
  60574. /** @hidden */
  60575. PhysicsViewer.prototype._updateDebugMeshes = function () {
  60576. var plugin = this._physicsEnginePlugin;
  60577. for (var i = 0; i < this._numMeshes; i++) {
  60578. var impostor = this._impostors[i];
  60579. if (!impostor) {
  60580. continue;
  60581. }
  60582. if (impostor.isDisposed) {
  60583. this.hideImpostor(this._impostors[i--]);
  60584. }
  60585. else {
  60586. var mesh = this._meshes[i];
  60587. if (mesh && plugin) {
  60588. plugin.syncMeshWithImpostor(mesh, impostor);
  60589. }
  60590. }
  60591. }
  60592. };
  60593. /**
  60594. * Renders a specified physic impostor
  60595. * @param impostor defines the impostor to render
  60596. */
  60597. PhysicsViewer.prototype.showImpostor = function (impostor) {
  60598. if (!this._scene) {
  60599. return;
  60600. }
  60601. for (var i = 0; i < this._numMeshes; i++) {
  60602. if (this._impostors[i] == impostor) {
  60603. return;
  60604. }
  60605. }
  60606. var debugMesh = this._getDebugMesh(impostor, this._scene);
  60607. if (debugMesh) {
  60608. this._impostors[this._numMeshes] = impostor;
  60609. this._meshes[this._numMeshes] = debugMesh;
  60610. if (this._numMeshes === 0) {
  60611. this._renderFunction = this._updateDebugMeshes.bind(this);
  60612. this._scene.registerBeforeRender(this._renderFunction);
  60613. }
  60614. this._numMeshes++;
  60615. }
  60616. };
  60617. /**
  60618. * Hides a specified physic impostor
  60619. * @param impostor defines the impostor to hide
  60620. */
  60621. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  60622. if (!impostor || !this._scene) {
  60623. return;
  60624. }
  60625. var removed = false;
  60626. for (var i = 0; i < this._numMeshes; i++) {
  60627. if (this._impostors[i] == impostor) {
  60628. var mesh = this._meshes[i];
  60629. if (!mesh) {
  60630. continue;
  60631. }
  60632. this._scene.removeMesh(mesh);
  60633. mesh.dispose();
  60634. this._numMeshes--;
  60635. if (this._numMeshes > 0) {
  60636. this._meshes[i] = this._meshes[this._numMeshes];
  60637. this._impostors[i] = this._impostors[this._numMeshes];
  60638. this._meshes[this._numMeshes] = null;
  60639. this._impostors[this._numMeshes] = null;
  60640. }
  60641. else {
  60642. this._meshes[0] = null;
  60643. this._impostors[0] = null;
  60644. }
  60645. removed = true;
  60646. break;
  60647. }
  60648. }
  60649. if (removed && this._numMeshes === 0) {
  60650. this._scene.unregisterBeforeRender(this._renderFunction);
  60651. }
  60652. };
  60653. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  60654. if (!this._debugMaterial) {
  60655. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  60656. this._debugMaterial.wireframe = true;
  60657. }
  60658. return this._debugMaterial;
  60659. };
  60660. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  60661. if (!this._debugBoxMesh) {
  60662. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  60663. this._debugBoxMesh.renderingGroupId = 1;
  60664. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  60665. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  60666. scene.removeMesh(this._debugBoxMesh);
  60667. }
  60668. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  60669. };
  60670. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  60671. if (!this._debugSphereMesh) {
  60672. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  60673. this._debugSphereMesh.renderingGroupId = 1;
  60674. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  60675. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  60676. scene.removeMesh(this._debugSphereMesh);
  60677. }
  60678. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  60679. };
  60680. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  60681. var mesh = null;
  60682. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  60683. mesh = this._getDebugBoxMesh(scene);
  60684. impostor.getBoxSizeToRef(mesh.scaling);
  60685. }
  60686. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  60687. mesh = this._getDebugSphereMesh(scene);
  60688. var radius = impostor.getRadius();
  60689. mesh.scaling.x = radius * 2;
  60690. mesh.scaling.y = radius * 2;
  60691. mesh.scaling.z = radius * 2;
  60692. }
  60693. return mesh;
  60694. };
  60695. /** Releases all resources */
  60696. PhysicsViewer.prototype.dispose = function () {
  60697. for (var i = 0; i < this._numMeshes; i++) {
  60698. this.hideImpostor(this._impostors[i]);
  60699. }
  60700. if (this._debugBoxMesh) {
  60701. this._debugBoxMesh.dispose();
  60702. }
  60703. if (this._debugSphereMesh) {
  60704. this._debugSphereMesh.dispose();
  60705. }
  60706. if (this._debugMaterial) {
  60707. this._debugMaterial.dispose();
  60708. }
  60709. this._impostors.length = 0;
  60710. this._scene = null;
  60711. this._physicsEnginePlugin = null;
  60712. };
  60713. return PhysicsViewer;
  60714. }());
  60715. Debug.PhysicsViewer = PhysicsViewer;
  60716. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60717. })(BABYLON || (BABYLON = {}));
  60718. //# sourceMappingURL=babylon.physicsViewer.js.map
  60719. var BABYLON;
  60720. (function (BABYLON) {
  60721. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  60722. get: function () {
  60723. return this._forceShowBoundingBoxes || false;
  60724. },
  60725. set: function (value) {
  60726. this._forceShowBoundingBoxes = value;
  60727. // Lazyly creates a BB renderer if needed.
  60728. if (value) {
  60729. this.getBoundingBoxRenderer();
  60730. }
  60731. },
  60732. enumerable: true,
  60733. configurable: true
  60734. });
  60735. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  60736. if (!this._boundingBoxRenderer) {
  60737. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  60738. }
  60739. return this._boundingBoxRenderer;
  60740. };
  60741. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  60742. get: function () {
  60743. return this._showBoundingBox || false;
  60744. },
  60745. set: function (value) {
  60746. this._showBoundingBox = value;
  60747. // Lazyly creates a BB renderer if needed.
  60748. if (value) {
  60749. this.getScene().getBoundingBoxRenderer();
  60750. }
  60751. },
  60752. enumerable: true,
  60753. configurable: true
  60754. });
  60755. var BoundingBoxRenderer = /** @class */ (function () {
  60756. function BoundingBoxRenderer(scene) {
  60757. /**
  60758. * The component name helpfull to identify the component in the list of scene components.
  60759. */
  60760. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  60761. this.frontColor = new BABYLON.Color3(1, 1, 1);
  60762. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  60763. this.showBackLines = true;
  60764. this.renderList = new BABYLON.SmartArray(32);
  60765. this._vertexBuffers = {};
  60766. this.scene = scene;
  60767. scene._addComponent(this);
  60768. }
  60769. /**
  60770. * Registers the component in a given scene
  60771. */
  60772. BoundingBoxRenderer.prototype.register = function () {
  60773. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  60774. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  60775. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  60776. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  60777. };
  60778. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  60779. if (mesh.showSubMeshesBoundingBox) {
  60780. var boundingInfo = subMesh.getBoundingInfo();
  60781. if (boundingInfo !== null && boundingInfo !== undefined) {
  60782. this.renderList.push(boundingInfo.boundingBox);
  60783. }
  60784. }
  60785. };
  60786. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  60787. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  60788. var boundingInfo = sourceMesh.getBoundingInfo();
  60789. this.renderList.push(boundingInfo.boundingBox);
  60790. }
  60791. };
  60792. BoundingBoxRenderer.prototype._prepareRessources = function () {
  60793. if (this._colorShader) {
  60794. return;
  60795. }
  60796. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  60797. attributes: [BABYLON.VertexBuffer.PositionKind],
  60798. uniforms: ["world", "viewProjection", "color"]
  60799. });
  60800. var engine = this.scene.getEngine();
  60801. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  60802. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  60803. this._createIndexBuffer();
  60804. };
  60805. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  60806. var engine = this.scene.getEngine();
  60807. 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]);
  60808. };
  60809. /**
  60810. * Rebuilds the elements related to this component in case of
  60811. * context lost for instance.
  60812. */
  60813. BoundingBoxRenderer.prototype.rebuild = function () {
  60814. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60815. if (vb) {
  60816. vb._rebuild();
  60817. }
  60818. this._createIndexBuffer();
  60819. };
  60820. BoundingBoxRenderer.prototype.reset = function () {
  60821. this.renderList.reset();
  60822. };
  60823. BoundingBoxRenderer.prototype.render = function () {
  60824. if (this.renderList.length === 0) {
  60825. return;
  60826. }
  60827. this._prepareRessources();
  60828. if (!this._colorShader.isReady()) {
  60829. return;
  60830. }
  60831. var engine = this.scene.getEngine();
  60832. engine.setDepthWrite(false);
  60833. this._colorShader._preBind();
  60834. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  60835. var boundingBox = this.renderList.data[boundingBoxIndex];
  60836. var min = boundingBox.minimum;
  60837. var max = boundingBox.maximum;
  60838. var diff = max.subtract(min);
  60839. var median = min.add(diff.scale(0.5));
  60840. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  60841. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  60842. .multiply(boundingBox.getWorldMatrix());
  60843. // VBOs
  60844. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  60845. if (this.showBackLines) {
  60846. // Back
  60847. engine.setDepthFunctionToGreaterOrEqual();
  60848. this.scene.resetCachedMaterial();
  60849. this._colorShader.setColor4("color", this.backColor.toColor4());
  60850. this._colorShader.bind(worldMatrix);
  60851. // Draw order
  60852. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  60853. }
  60854. // Front
  60855. engine.setDepthFunctionToLess();
  60856. this.scene.resetCachedMaterial();
  60857. this._colorShader.setColor4("color", this.frontColor.toColor4());
  60858. this._colorShader.bind(worldMatrix);
  60859. // Draw order
  60860. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  60861. }
  60862. this._colorShader.unbind();
  60863. engine.setDepthFunctionToLessOrEqual();
  60864. engine.setDepthWrite(true);
  60865. };
  60866. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  60867. this._prepareRessources();
  60868. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  60869. return;
  60870. }
  60871. var engine = this.scene.getEngine();
  60872. engine.setDepthWrite(false);
  60873. engine.setColorWrite(false);
  60874. this._colorShader._preBind();
  60875. var boundingBox = mesh._boundingInfo.boundingBox;
  60876. var min = boundingBox.minimum;
  60877. var max = boundingBox.maximum;
  60878. var diff = max.subtract(min);
  60879. var median = min.add(diff.scale(0.5));
  60880. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  60881. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  60882. .multiply(boundingBox.getWorldMatrix());
  60883. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  60884. engine.setDepthFunctionToLess();
  60885. this.scene.resetCachedMaterial();
  60886. this._colorShader.bind(worldMatrix);
  60887. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  60888. this._colorShader.unbind();
  60889. engine.setDepthFunctionToLessOrEqual();
  60890. engine.setDepthWrite(true);
  60891. engine.setColorWrite(true);
  60892. };
  60893. BoundingBoxRenderer.prototype.dispose = function () {
  60894. if (!this._colorShader) {
  60895. return;
  60896. }
  60897. this.renderList.dispose();
  60898. this._colorShader.dispose();
  60899. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60900. if (buffer) {
  60901. buffer.dispose();
  60902. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  60903. }
  60904. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  60905. };
  60906. return BoundingBoxRenderer;
  60907. }());
  60908. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  60909. })(BABYLON || (BABYLON = {}));
  60910. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  60911. var BABYLON;
  60912. (function (BABYLON) {
  60913. BABYLON.Engine.prototype.createTransformFeedback = function () {
  60914. return this._gl.createTransformFeedback();
  60915. };
  60916. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  60917. this._gl.deleteTransformFeedback(value);
  60918. };
  60919. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  60920. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  60921. };
  60922. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  60923. if (usePoints === void 0) { usePoints = true; }
  60924. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  60925. };
  60926. BABYLON.Engine.prototype.endTransformFeedback = function () {
  60927. this._gl.endTransformFeedback();
  60928. };
  60929. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  60930. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  60931. };
  60932. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  60933. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  60934. };
  60935. })(BABYLON || (BABYLON = {}));
  60936. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  60937. var BABYLON;
  60938. (function (BABYLON) {
  60939. /**
  60940. * This represents a GPU particle system in Babylon
  60941. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  60942. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  60943. */
  60944. var GPUParticleSystem = /** @class */ (function (_super) {
  60945. __extends(GPUParticleSystem, _super);
  60946. /**
  60947. * Instantiates a GPU particle system.
  60948. * 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.
  60949. * @param name The name of the particle system
  60950. * @param options The options used to create the system
  60951. * @param scene The scene the particle system belongs to
  60952. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  60953. */
  60954. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  60955. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60956. var _this = _super.call(this, name) || this;
  60957. /**
  60958. * The layer mask we are rendering the particles through.
  60959. */
  60960. _this.layerMask = 0x0FFFFFFF;
  60961. _this._accumulatedCount = 0;
  60962. _this._targetIndex = 0;
  60963. _this._currentRenderId = -1;
  60964. _this._started = false;
  60965. _this._stopped = false;
  60966. _this._timeDelta = 0;
  60967. _this._attributesStrideSize = 21;
  60968. _this._actualFrame = 0;
  60969. _this._rawTextureWidth = 256;
  60970. /**
  60971. * An event triggered when the system is disposed.
  60972. */
  60973. _this.onDisposeObservable = new BABYLON.Observable();
  60974. /**
  60975. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  60976. * to override the particles.
  60977. */
  60978. _this.forceDepthWrite = false;
  60979. _this._preWarmDone = false;
  60980. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60981. // Setup the default processing configuration to the scene.
  60982. _this._attachImageProcessingConfiguration(null);
  60983. _this._engine = _this._scene.getEngine();
  60984. if (!options.randomTextureSize) {
  60985. delete options.randomTextureSize;
  60986. }
  60987. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  60988. var optionsAsNumber = options;
  60989. if (isFinite(optionsAsNumber)) {
  60990. fullOptions.capacity = optionsAsNumber;
  60991. }
  60992. _this._capacity = fullOptions.capacity;
  60993. _this._activeCount = fullOptions.capacity;
  60994. _this._currentActiveCount = 0;
  60995. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  60996. _this._scene.particleSystems.push(_this);
  60997. _this._updateEffectOptions = {
  60998. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  60999. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  61000. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  61001. "angleRange", "radiusRange", "cellInfos", "noiseStrength"],
  61002. uniformBuffersNames: [],
  61003. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "noiseSampler"],
  61004. defines: "",
  61005. fallbacks: null,
  61006. onCompiled: null,
  61007. onError: null,
  61008. indexParameters: null,
  61009. maxSimultaneousLights: 0,
  61010. transformFeedbackVaryings: []
  61011. };
  61012. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  61013. // Random data
  61014. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  61015. var d = [];
  61016. for (var i = 0; i < maxTextureSize; ++i) {
  61017. d.push(Math.random());
  61018. d.push(Math.random());
  61019. d.push(Math.random());
  61020. d.push(Math.random());
  61021. }
  61022. _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);
  61023. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61024. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61025. d = [];
  61026. for (var i = 0; i < maxTextureSize; ++i) {
  61027. d.push(Math.random());
  61028. d.push(Math.random());
  61029. d.push(Math.random());
  61030. d.push(Math.random());
  61031. }
  61032. _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);
  61033. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61034. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61035. _this._randomTextureSize = maxTextureSize;
  61036. return _this;
  61037. }
  61038. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  61039. /**
  61040. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  61041. */
  61042. get: function () {
  61043. if (!BABYLON.Engine.LastCreatedEngine) {
  61044. return false;
  61045. }
  61046. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  61047. },
  61048. enumerable: true,
  61049. configurable: true
  61050. });
  61051. /**
  61052. * Gets the maximum number of particles active at the same time.
  61053. * @returns The max number of active particles.
  61054. */
  61055. GPUParticleSystem.prototype.getCapacity = function () {
  61056. return this._capacity;
  61057. };
  61058. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  61059. /**
  61060. * Gets or set the number of active particles
  61061. */
  61062. get: function () {
  61063. return this._activeCount;
  61064. },
  61065. set: function (value) {
  61066. this._activeCount = Math.min(value, this._capacity);
  61067. },
  61068. enumerable: true,
  61069. configurable: true
  61070. });
  61071. /**
  61072. * Is this system ready to be used/rendered
  61073. * @return true if the system is ready
  61074. */
  61075. GPUParticleSystem.prototype.isReady = function () {
  61076. if (!this._updateEffect) {
  61077. this._recreateUpdateEffect();
  61078. this._recreateRenderEffect();
  61079. return false;
  61080. }
  61081. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  61082. return false;
  61083. }
  61084. return true;
  61085. };
  61086. /**
  61087. * Gets if the system has been started. (Note: this will still be true after stop is called)
  61088. * @returns True if it has been started, otherwise false.
  61089. */
  61090. GPUParticleSystem.prototype.isStarted = function () {
  61091. return this._started;
  61092. };
  61093. /**
  61094. * Starts the particle system and begins to emit
  61095. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  61096. */
  61097. GPUParticleSystem.prototype.start = function (delay) {
  61098. var _this = this;
  61099. if (delay === void 0) { delay = 0; }
  61100. if (delay) {
  61101. setTimeout(function () {
  61102. _this.start(0);
  61103. }, delay);
  61104. return;
  61105. }
  61106. this._started = true;
  61107. this._stopped = false;
  61108. this._preWarmDone = false;
  61109. };
  61110. /**
  61111. * Stops the particle system.
  61112. */
  61113. GPUParticleSystem.prototype.stop = function () {
  61114. this._stopped = true;
  61115. };
  61116. /**
  61117. * Remove all active particles
  61118. */
  61119. GPUParticleSystem.prototype.reset = function () {
  61120. this._releaseBuffers();
  61121. this._releaseVAOs();
  61122. this._currentActiveCount = 0;
  61123. this._targetIndex = 0;
  61124. };
  61125. /**
  61126. * Returns the string "GPUParticleSystem"
  61127. * @returns a string containing the class name
  61128. */
  61129. GPUParticleSystem.prototype.getClassName = function () {
  61130. return "GPUParticleSystem";
  61131. };
  61132. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  61133. if (!gradients) {
  61134. return this;
  61135. }
  61136. var index = 0;
  61137. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  61138. var valueGradient = gradients_1[_i];
  61139. if (valueGradient.gradient === gradient) {
  61140. gradients.splice(index, 1);
  61141. break;
  61142. }
  61143. index++;
  61144. }
  61145. if (texture) {
  61146. texture.dispose();
  61147. }
  61148. this._releaseBuffers();
  61149. return this;
  61150. };
  61151. /**
  61152. * Adds a new color gradient
  61153. * @param gradient defines the gradient to use (between 0 and 1)
  61154. * @param color defines the color to affect to the specified gradient
  61155. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  61156. * @returns the current particle system
  61157. */
  61158. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  61159. if (!this._colorGradients) {
  61160. this._colorGradients = [];
  61161. }
  61162. var colorGradient = new BABYLON.ColorGradient();
  61163. colorGradient.gradient = gradient;
  61164. colorGradient.color1 = color1;
  61165. this._colorGradients.push(colorGradient);
  61166. this._colorGradients.sort(function (a, b) {
  61167. if (a.gradient < b.gradient) {
  61168. return -1;
  61169. }
  61170. else if (a.gradient > b.gradient) {
  61171. return 1;
  61172. }
  61173. return 0;
  61174. });
  61175. if (this._colorGradientsTexture) {
  61176. this._colorGradientsTexture.dispose();
  61177. this._colorGradientsTexture = null;
  61178. }
  61179. this._releaseBuffers();
  61180. return this;
  61181. };
  61182. /**
  61183. * Remove a specific color gradient
  61184. * @param gradient defines the gradient to remove
  61185. * @returns the current particle system
  61186. */
  61187. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  61188. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  61189. this._colorGradientsTexture = null;
  61190. return this;
  61191. };
  61192. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  61193. var valueGradient = new BABYLON.FactorGradient();
  61194. valueGradient.gradient = gradient;
  61195. valueGradient.factor1 = factor;
  61196. factorGradients.push(valueGradient);
  61197. factorGradients.sort(function (a, b) {
  61198. if (a.gradient < b.gradient) {
  61199. return -1;
  61200. }
  61201. else if (a.gradient > b.gradient) {
  61202. return 1;
  61203. }
  61204. return 0;
  61205. });
  61206. this._releaseBuffers();
  61207. };
  61208. /**
  61209. * Adds a new size gradient
  61210. * @param gradient defines the gradient to use (between 0 and 1)
  61211. * @param factor defines the size factor to affect to the specified gradient
  61212. * @returns the current particle system
  61213. */
  61214. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  61215. if (!this._sizeGradients) {
  61216. this._sizeGradients = [];
  61217. }
  61218. this._addFactorGradient(this._sizeGradients, gradient, factor);
  61219. if (this._sizeGradientsTexture) {
  61220. this._sizeGradientsTexture.dispose();
  61221. this._sizeGradientsTexture = null;
  61222. }
  61223. this._releaseBuffers();
  61224. return this;
  61225. };
  61226. /**
  61227. * Remove a specific size gradient
  61228. * @param gradient defines the gradient to remove
  61229. * @returns the current particle system
  61230. */
  61231. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  61232. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  61233. this._sizeGradientsTexture = null;
  61234. return this;
  61235. };
  61236. /**
  61237. * Adds a new angular speed gradient
  61238. * @param gradient defines the gradient to use (between 0 and 1)
  61239. * @param factor defines the angular speed to affect to the specified gradient
  61240. * @returns the current particle system
  61241. */
  61242. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  61243. if (!this._angularSpeedGradients) {
  61244. this._angularSpeedGradients = [];
  61245. }
  61246. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  61247. if (this._angularSpeedGradientsTexture) {
  61248. this._angularSpeedGradientsTexture.dispose();
  61249. this._angularSpeedGradientsTexture = null;
  61250. }
  61251. this._releaseBuffers();
  61252. return this;
  61253. };
  61254. /**
  61255. * Remove a specific angular speed gradient
  61256. * @param gradient defines the gradient to remove
  61257. * @returns the current particle system
  61258. */
  61259. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  61260. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  61261. this._angularSpeedGradientsTexture = null;
  61262. return this;
  61263. };
  61264. /**
  61265. * Adds a new velocity gradient
  61266. * @param gradient defines the gradient to use (between 0 and 1)
  61267. * @param factor defines the velocity to affect to the specified gradient
  61268. * @returns the current particle system
  61269. */
  61270. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  61271. if (!this._velocityGradients) {
  61272. this._velocityGradients = [];
  61273. }
  61274. this._addFactorGradient(this._velocityGradients, gradient, factor);
  61275. if (this._velocityGradientsTexture) {
  61276. this._velocityGradientsTexture.dispose();
  61277. this._velocityGradientsTexture = null;
  61278. }
  61279. this._releaseBuffers();
  61280. return this;
  61281. };
  61282. /**
  61283. * Remove a specific velocity gradient
  61284. * @param gradient defines the gradient to remove
  61285. * @returns the current particle system
  61286. */
  61287. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  61288. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  61289. this._velocityGradientsTexture = null;
  61290. return this;
  61291. };
  61292. /**
  61293. * Adds a new limit velocity gradient
  61294. * @param gradient defines the gradient to use (between 0 and 1)
  61295. * @param factor defines the limit velocity value to affect to the specified gradient
  61296. * @returns the current particle system
  61297. */
  61298. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  61299. if (!this._limitVelocityGradients) {
  61300. this._limitVelocityGradients = [];
  61301. }
  61302. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  61303. if (this._limitVelocityGradientsTexture) {
  61304. this._limitVelocityGradientsTexture.dispose();
  61305. this._limitVelocityGradientsTexture = null;
  61306. }
  61307. this._releaseBuffers();
  61308. return this;
  61309. };
  61310. /**
  61311. * Remove a specific limit velocity gradient
  61312. * @param gradient defines the gradient to remove
  61313. * @returns the current particle system
  61314. */
  61315. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  61316. this._removeGradient(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  61317. this._limitVelocityGradientsTexture = null;
  61318. return this;
  61319. };
  61320. /**
  61321. * Adds a new drag gradient
  61322. * @param gradient defines the gradient to use (between 0 and 1)
  61323. * @param factor defines the drag value to affect to the specified gradient
  61324. * @returns the current particle system
  61325. */
  61326. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  61327. if (!this._dragGradients) {
  61328. this._dragGradients = [];
  61329. }
  61330. this._addFactorGradient(this._dragGradients, gradient, factor);
  61331. if (this._dragGradientsTexture) {
  61332. this._dragGradientsTexture.dispose();
  61333. this._dragGradientsTexture = null;
  61334. }
  61335. this._releaseBuffers();
  61336. return this;
  61337. };
  61338. /**
  61339. * Remove a specific drag gradient
  61340. * @param gradient defines the gradient to remove
  61341. * @returns the current particle system
  61342. */
  61343. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  61344. this._removeGradient(gradient, this._dragGradients, this._dragGradientsTexture);
  61345. this._dragGradientsTexture = null;
  61346. return this;
  61347. };
  61348. /**
  61349. * Not supported by GPUParticleSystem
  61350. * @param gradient defines the gradient to use (between 0 and 1)
  61351. * @param factor defines the emit rate value to affect to the specified gradient
  61352. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61353. * @returns the current particle system
  61354. */
  61355. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  61356. // Do nothing as emit rate is not supported by GPUParticleSystem
  61357. return this;
  61358. };
  61359. /**
  61360. * Not supported by GPUParticleSystem
  61361. * @param gradient defines the gradient to remove
  61362. * @returns the current particle system
  61363. */
  61364. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  61365. // Do nothing as emit rate is not supported by GPUParticleSystem
  61366. return this;
  61367. };
  61368. GPUParticleSystem.prototype._reset = function () {
  61369. this._releaseBuffers();
  61370. };
  61371. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  61372. var updateVertexBuffers = {};
  61373. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  61374. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  61375. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  61376. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  61377. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  61378. var offset = 12;
  61379. if (!this._colorGradientsTexture) {
  61380. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  61381. offset += 4;
  61382. }
  61383. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  61384. offset += 3;
  61385. if (!this._isBillboardBased) {
  61386. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  61387. offset += 3;
  61388. }
  61389. if (this._angularSpeedGradientsTexture) {
  61390. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  61391. offset += 1;
  61392. }
  61393. else {
  61394. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  61395. offset += 2;
  61396. }
  61397. if (this._isAnimationSheetEnabled) {
  61398. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  61399. offset += 1;
  61400. }
  61401. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  61402. this._engine.bindArrayBuffer(null);
  61403. return vao;
  61404. };
  61405. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  61406. var renderVertexBuffers = {};
  61407. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  61408. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  61409. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  61410. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  61411. var offset = 12;
  61412. if (!this._colorGradientsTexture) {
  61413. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  61414. offset += 4;
  61415. }
  61416. offset += 3; // Direction
  61417. if (!this._isBillboardBased) {
  61418. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  61419. offset += 3;
  61420. }
  61421. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  61422. if (this._angularSpeedGradientsTexture) {
  61423. offset++;
  61424. }
  61425. else {
  61426. offset += 2;
  61427. }
  61428. if (this._isAnimationSheetEnabled) {
  61429. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  61430. offset += 1;
  61431. }
  61432. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  61433. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  61434. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  61435. this._engine.bindArrayBuffer(null);
  61436. return vao;
  61437. };
  61438. GPUParticleSystem.prototype._initialize = function (force) {
  61439. if (force === void 0) { force = false; }
  61440. if (this._buffer0 && !force) {
  61441. return;
  61442. }
  61443. var engine = this._scene.getEngine();
  61444. var data = new Array();
  61445. if (!this.isBillboardBased) {
  61446. this._attributesStrideSize += 3;
  61447. }
  61448. if (this._colorGradientsTexture) {
  61449. this._attributesStrideSize -= 4;
  61450. }
  61451. if (this._angularSpeedGradientsTexture) {
  61452. this._attributesStrideSize -= 1;
  61453. }
  61454. if (this._isAnimationSheetEnabled) {
  61455. this._attributesStrideSize += 1;
  61456. }
  61457. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  61458. // position
  61459. data.push(0.0);
  61460. data.push(0.0);
  61461. data.push(0.0);
  61462. // Age and life
  61463. data.push(0.0); // create the particle as a dead one to create a new one at start
  61464. data.push(0.0);
  61465. // Seed
  61466. data.push(Math.random());
  61467. data.push(Math.random());
  61468. data.push(Math.random());
  61469. data.push(Math.random());
  61470. // Size
  61471. data.push(0.0);
  61472. data.push(0.0);
  61473. data.push(0.0);
  61474. if (!this._colorGradientsTexture) {
  61475. // color
  61476. data.push(0.0);
  61477. data.push(0.0);
  61478. data.push(0.0);
  61479. data.push(0.0);
  61480. }
  61481. // direction
  61482. data.push(0.0);
  61483. data.push(0.0);
  61484. data.push(0.0);
  61485. if (!this.isBillboardBased) {
  61486. // initialDirection
  61487. data.push(0.0);
  61488. data.push(0.0);
  61489. data.push(0.0);
  61490. }
  61491. // angle
  61492. data.push(0.0);
  61493. if (!this._angularSpeedGradientsTexture) {
  61494. data.push(0.0);
  61495. }
  61496. if (this._isAnimationSheetEnabled) {
  61497. data.push(0.0);
  61498. }
  61499. }
  61500. // Sprite data
  61501. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  61502. -0.5, 0.5, 0, 1,
  61503. -0.5, -0.5, 0, 0,
  61504. 0.5, -0.5, 1, 0]);
  61505. // Buffers
  61506. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  61507. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  61508. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  61509. // Update VAO
  61510. this._updateVAO = [];
  61511. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  61512. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  61513. // Render VAO
  61514. this._renderVAO = [];
  61515. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  61516. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  61517. // Links
  61518. this._sourceBuffer = this._buffer0;
  61519. this._targetBuffer = this._buffer1;
  61520. };
  61521. /** @hidden */
  61522. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  61523. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  61524. if (this._isBillboardBased) {
  61525. defines += "\n#define BILLBOARD";
  61526. }
  61527. if (this._colorGradientsTexture) {
  61528. defines += "\n#define COLORGRADIENTS";
  61529. }
  61530. if (this._sizeGradientsTexture) {
  61531. defines += "\n#define SIZEGRADIENTS";
  61532. }
  61533. if (this._angularSpeedGradientsTexture) {
  61534. defines += "\n#define ANGULARSPEEDGRADIENTS";
  61535. }
  61536. if (this._velocityGradientsTexture) {
  61537. defines += "\n#define VELOCITYGRADIENTS";
  61538. }
  61539. if (this.isAnimationSheetEnabled) {
  61540. defines += "\n#define ANIMATESHEET";
  61541. }
  61542. if (this.noiseTexture) {
  61543. defines += "\n#define NOISE";
  61544. }
  61545. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  61546. return;
  61547. }
  61548. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  61549. if (!this._colorGradientsTexture) {
  61550. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  61551. }
  61552. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  61553. if (!this._isBillboardBased) {
  61554. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  61555. }
  61556. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  61557. if (this.isAnimationSheetEnabled) {
  61558. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  61559. }
  61560. this._updateEffectOptions.defines = defines;
  61561. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  61562. };
  61563. /** @hidden */
  61564. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  61565. var defines = "";
  61566. if (this._scene.clipPlane) {
  61567. defines = "\n#define CLIPPLANE";
  61568. }
  61569. if (this._scene.clipPlane2) {
  61570. defines = "\n#define CLIPPLANE2";
  61571. }
  61572. if (this._scene.clipPlane3) {
  61573. defines = "\n#define CLIPPLANE3";
  61574. }
  61575. if (this._scene.clipPlane4) {
  61576. defines = "\n#define CLIPPLANE4";
  61577. }
  61578. if (this._isBillboardBased) {
  61579. defines += "\n#define BILLBOARD";
  61580. switch (this.billboardMode) {
  61581. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  61582. defines += "\n#define BILLBOARDY";
  61583. break;
  61584. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  61585. default:
  61586. break;
  61587. }
  61588. }
  61589. if (this._colorGradientsTexture) {
  61590. defines += "\n#define COLORGRADIENTS";
  61591. }
  61592. if (this.isAnimationSheetEnabled) {
  61593. defines += "\n#define ANIMATESHEET";
  61594. }
  61595. if (this._imageProcessingConfiguration) {
  61596. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  61597. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  61598. }
  61599. if (this._renderEffect && this._renderEffect.defines === defines) {
  61600. return;
  61601. }
  61602. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  61603. var samplers = ["textureSampler", "colorGradientSampler"];
  61604. if (BABYLON.ImageProcessingConfiguration) {
  61605. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  61606. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  61607. }
  61608. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  61609. };
  61610. /**
  61611. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  61612. * @param preWarm defines if we are in the pre-warmimg phase
  61613. */
  61614. GPUParticleSystem.prototype.animate = function (preWarm) {
  61615. if (preWarm === void 0) { preWarm = false; }
  61616. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  61617. this._actualFrame += this._timeDelta;
  61618. if (!this._stopped) {
  61619. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  61620. this.stop();
  61621. }
  61622. }
  61623. };
  61624. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  61625. var texture = this[textureName];
  61626. if (!factorGradients || !factorGradients.length || texture) {
  61627. return;
  61628. }
  61629. var data = new Float32Array(this._rawTextureWidth);
  61630. for (var x = 0; x < this._rawTextureWidth; x++) {
  61631. var ratio = x / this._rawTextureWidth;
  61632. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  61633. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  61634. });
  61635. }
  61636. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61637. };
  61638. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  61639. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  61640. };
  61641. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  61642. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  61643. };
  61644. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  61645. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  61646. };
  61647. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  61648. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  61649. return;
  61650. }
  61651. var data = new Uint8Array(this._rawTextureWidth * 4);
  61652. var tmpColor = BABYLON.Tmp.Color4[0];
  61653. for (var x = 0; x < this._rawTextureWidth; x++) {
  61654. var ratio = x / this._rawTextureWidth;
  61655. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  61656. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  61657. data[x * 4] = tmpColor.r * 255;
  61658. data[x * 4 + 1] = tmpColor.g * 255;
  61659. data[x * 4 + 2] = tmpColor.b * 255;
  61660. data[x * 4 + 3] = tmpColor.a * 255;
  61661. });
  61662. }
  61663. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61664. };
  61665. /**
  61666. * Renders the particle system in its current state
  61667. * @param preWarm defines if the system should only update the particles but not render them
  61668. * @returns the current number of particles
  61669. */
  61670. GPUParticleSystem.prototype.render = function (preWarm) {
  61671. if (preWarm === void 0) { preWarm = false; }
  61672. if (!this._started) {
  61673. return 0;
  61674. }
  61675. this._createColorGradientTexture();
  61676. this._createSizeGradientTexture();
  61677. this._createAngularSpeedGradientTexture();
  61678. this._createVelocityGradientTexture();
  61679. this._recreateUpdateEffect();
  61680. this._recreateRenderEffect();
  61681. if (!this.isReady()) {
  61682. return 0;
  61683. }
  61684. if (!preWarm) {
  61685. if (!this._preWarmDone && this.preWarmCycles) {
  61686. for (var index = 0; index < this.preWarmCycles; index++) {
  61687. this.animate(true);
  61688. this.render(true);
  61689. }
  61690. this._preWarmDone = true;
  61691. }
  61692. if (this._currentRenderId === this._scene.getRenderId()) {
  61693. return 0;
  61694. }
  61695. this._currentRenderId = this._scene.getRenderId();
  61696. }
  61697. // Get everything ready to render
  61698. this._initialize();
  61699. this._accumulatedCount += this.emitRate * this._timeDelta;
  61700. if (this._accumulatedCount > 1) {
  61701. var intPart = this._accumulatedCount | 0;
  61702. this._accumulatedCount -= intPart;
  61703. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  61704. }
  61705. if (!this._currentActiveCount) {
  61706. return 0;
  61707. }
  61708. // Enable update effect
  61709. this._engine.enableEffect(this._updateEffect);
  61710. this._engine.setState(false);
  61711. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  61712. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  61713. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  61714. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  61715. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  61716. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  61717. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  61718. if (!this._colorGradientsTexture) {
  61719. this._updateEffect.setDirectColor4("color1", this.color1);
  61720. this._updateEffect.setDirectColor4("color2", this.color2);
  61721. }
  61722. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  61723. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  61724. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  61725. this._updateEffect.setVector3("gravity", this.gravity);
  61726. if (this._sizeGradientsTexture) {
  61727. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  61728. }
  61729. if (this._angularSpeedGradientsTexture) {
  61730. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  61731. }
  61732. if (this._velocityGradientsTexture) {
  61733. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  61734. }
  61735. if (this.particleEmitterType) {
  61736. this.particleEmitterType.applyToShader(this._updateEffect);
  61737. }
  61738. if (this._isAnimationSheetEnabled) {
  61739. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  61740. }
  61741. if (this.noiseTexture) {
  61742. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  61743. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  61744. }
  61745. var emitterWM;
  61746. if (this.emitter.position) {
  61747. var emitterMesh = this.emitter;
  61748. emitterWM = emitterMesh.getWorldMatrix();
  61749. }
  61750. else {
  61751. var emitterPosition = this.emitter;
  61752. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  61753. }
  61754. this._updateEffect.setMatrix("emitterWM", emitterWM);
  61755. // Bind source VAO
  61756. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  61757. // Update
  61758. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  61759. this._engine.setRasterizerState(false);
  61760. this._engine.beginTransformFeedback(true);
  61761. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  61762. this._engine.endTransformFeedback();
  61763. this._engine.setRasterizerState(true);
  61764. this._engine.bindTransformFeedbackBuffer(null);
  61765. if (!preWarm) {
  61766. // Enable render effect
  61767. this._engine.enableEffect(this._renderEffect);
  61768. var viewMatrix = this._scene.getViewMatrix();
  61769. this._renderEffect.setMatrix("view", viewMatrix);
  61770. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  61771. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  61772. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  61773. if (this._colorGradientsTexture) {
  61774. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  61775. }
  61776. else {
  61777. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  61778. }
  61779. if (this._isAnimationSheetEnabled && this.particleTexture) {
  61780. var baseSize = this.particleTexture.getBaseSize();
  61781. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  61782. }
  61783. if (this._isBillboardBased) {
  61784. var camera = this._scene.activeCamera;
  61785. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  61786. }
  61787. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  61788. var invView = viewMatrix.clone();
  61789. invView.invert();
  61790. this._renderEffect.setMatrix("invView", invView);
  61791. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  61792. }
  61793. // image processing
  61794. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  61795. this._imageProcessingConfiguration.bind(this._renderEffect);
  61796. }
  61797. // Draw order
  61798. switch (this.blendMode) {
  61799. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  61800. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  61801. break;
  61802. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  61803. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  61804. break;
  61805. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  61806. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  61807. break;
  61808. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  61809. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  61810. break;
  61811. }
  61812. if (this.forceDepthWrite) {
  61813. this._engine.setDepthWrite(true);
  61814. }
  61815. // Bind source VAO
  61816. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  61817. // Render
  61818. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  61819. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  61820. }
  61821. // Switch VAOs
  61822. this._targetIndex++;
  61823. if (this._targetIndex === 2) {
  61824. this._targetIndex = 0;
  61825. }
  61826. // Switch buffers
  61827. var tmpBuffer = this._sourceBuffer;
  61828. this._sourceBuffer = this._targetBuffer;
  61829. this._targetBuffer = tmpBuffer;
  61830. return this._currentActiveCount;
  61831. };
  61832. /**
  61833. * Rebuilds the particle system
  61834. */
  61835. GPUParticleSystem.prototype.rebuild = function () {
  61836. this._initialize(true);
  61837. };
  61838. GPUParticleSystem.prototype._releaseBuffers = function () {
  61839. if (this._buffer0) {
  61840. this._buffer0.dispose();
  61841. this._buffer0 = null;
  61842. }
  61843. if (this._buffer1) {
  61844. this._buffer1.dispose();
  61845. this._buffer1 = null;
  61846. }
  61847. if (this._spriteBuffer) {
  61848. this._spriteBuffer.dispose();
  61849. this._spriteBuffer = null;
  61850. }
  61851. };
  61852. GPUParticleSystem.prototype._releaseVAOs = function () {
  61853. if (!this._updateVAO) {
  61854. return;
  61855. }
  61856. for (var index = 0; index < this._updateVAO.length; index++) {
  61857. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  61858. }
  61859. this._updateVAO = [];
  61860. for (var index = 0; index < this._renderVAO.length; index++) {
  61861. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  61862. }
  61863. this._renderVAO = [];
  61864. };
  61865. /**
  61866. * Disposes the particle system and free the associated resources
  61867. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  61868. */
  61869. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  61870. if (disposeTexture === void 0) { disposeTexture = true; }
  61871. var index = this._scene.particleSystems.indexOf(this);
  61872. if (index > -1) {
  61873. this._scene.particleSystems.splice(index, 1);
  61874. }
  61875. this._releaseBuffers();
  61876. this._releaseVAOs();
  61877. if (this._colorGradientsTexture) {
  61878. this._colorGradientsTexture.dispose();
  61879. this._colorGradientsTexture = null;
  61880. }
  61881. if (this._sizeGradientsTexture) {
  61882. this._sizeGradientsTexture.dispose();
  61883. this._sizeGradientsTexture = null;
  61884. }
  61885. if (this._angularSpeedGradientsTexture) {
  61886. this._angularSpeedGradientsTexture.dispose();
  61887. this._angularSpeedGradientsTexture = null;
  61888. }
  61889. if (this._velocityGradientsTexture) {
  61890. this._velocityGradientsTexture.dispose();
  61891. this._velocityGradientsTexture = null;
  61892. }
  61893. if (this._limitVelocityGradientsTexture) {
  61894. this._limitVelocityGradientsTexture.dispose();
  61895. this._limitVelocityGradientsTexture = null;
  61896. }
  61897. if (this._randomTexture) {
  61898. this._randomTexture.dispose();
  61899. this._randomTexture = null;
  61900. }
  61901. if (this._randomTexture2) {
  61902. this._randomTexture2.dispose();
  61903. this._randomTexture2 = null;
  61904. }
  61905. if (disposeTexture && this.particleTexture) {
  61906. this.particleTexture.dispose();
  61907. this.particleTexture = null;
  61908. }
  61909. if (disposeTexture && this.noiseTexture) {
  61910. this.noiseTexture.dispose();
  61911. this.noiseTexture = null;
  61912. }
  61913. // Callback
  61914. this.onDisposeObservable.notifyObservers(this);
  61915. this.onDisposeObservable.clear();
  61916. };
  61917. /**
  61918. * Clones the particle system.
  61919. * @param name The name of the cloned object
  61920. * @param newEmitter The new emitter to use
  61921. * @returns the cloned particle system
  61922. */
  61923. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  61924. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  61925. BABYLON.Tools.DeepCopy(this, result);
  61926. if (newEmitter === undefined) {
  61927. newEmitter = this.emitter;
  61928. }
  61929. result.emitter = newEmitter;
  61930. if (this.particleTexture) {
  61931. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  61932. }
  61933. return result;
  61934. };
  61935. /**
  61936. * Serializes the particle system to a JSON object.
  61937. * @returns the JSON object
  61938. */
  61939. GPUParticleSystem.prototype.serialize = function () {
  61940. var serializationObject = {};
  61941. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  61942. serializationObject.activeParticleCount = this.activeParticleCount;
  61943. return serializationObject;
  61944. };
  61945. /**
  61946. * Parses a JSON object to create a GPU particle system.
  61947. * @param parsedParticleSystem The JSON object to parse
  61948. * @param scene The scene to create the particle system in
  61949. * @param rootUrl The root url to use to load external dependencies like texture
  61950. * @returns the parsed GPU particle system
  61951. */
  61952. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  61953. var name = parsedParticleSystem.name;
  61954. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  61955. if (parsedParticleSystem.activeParticleCount) {
  61956. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  61957. }
  61958. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  61959. return particleSystem;
  61960. };
  61961. return GPUParticleSystem;
  61962. }(BABYLON.BaseParticleSystem));
  61963. BABYLON.GPUParticleSystem = GPUParticleSystem;
  61964. })(BABYLON || (BABYLON = {}));
  61965. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  61966. var BABYLON;
  61967. (function (BABYLON) {
  61968. /**
  61969. * Represents one particle of a solid particle system.
  61970. */
  61971. var SolidParticle = /** @class */ (function () {
  61972. /**
  61973. * Creates a Solid Particle object.
  61974. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  61975. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  61976. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  61977. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  61978. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  61979. * @param shapeId (integer) is the model shape identifier in the SPS.
  61980. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  61981. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  61982. */
  61983. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  61984. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  61985. /**
  61986. * particle global index
  61987. */
  61988. this.idx = 0;
  61989. /**
  61990. * The color of the particle
  61991. */
  61992. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  61993. /**
  61994. * The world space position of the particle.
  61995. */
  61996. this.position = BABYLON.Vector3.Zero();
  61997. /**
  61998. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  61999. */
  62000. this.rotation = BABYLON.Vector3.Zero();
  62001. /**
  62002. * The scaling of the particle.
  62003. */
  62004. this.scaling = BABYLON.Vector3.One();
  62005. /**
  62006. * The uvs of the particle.
  62007. */
  62008. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  62009. /**
  62010. * The current speed of the particle.
  62011. */
  62012. this.velocity = BABYLON.Vector3.Zero();
  62013. /**
  62014. * The pivot point in the particle local space.
  62015. */
  62016. this.pivot = BABYLON.Vector3.Zero();
  62017. /**
  62018. * Must the particle be translated from its pivot point in its local space ?
  62019. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  62020. * Default : false
  62021. */
  62022. this.translateFromPivot = false;
  62023. /**
  62024. * Is the particle active or not ?
  62025. */
  62026. this.alive = true;
  62027. /**
  62028. * Is the particle visible or not ?
  62029. */
  62030. this.isVisible = true;
  62031. /**
  62032. * Index of this particle in the global "positions" array (Internal use)
  62033. * @hidden
  62034. */
  62035. this._pos = 0;
  62036. /**
  62037. * @hidden Index of this particle in the global "indices" array (Internal use)
  62038. */
  62039. this._ind = 0;
  62040. /**
  62041. * ModelShape id of this particle
  62042. */
  62043. this.shapeId = 0;
  62044. /**
  62045. * Index of the particle in its shape id (Internal use)
  62046. */
  62047. this.idxInShape = 0;
  62048. /**
  62049. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  62050. */
  62051. this._stillInvisible = false;
  62052. /**
  62053. * @hidden Last computed particle rotation matrix
  62054. */
  62055. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  62056. /**
  62057. * Parent particle Id, if any.
  62058. * Default null.
  62059. */
  62060. this.parentId = null;
  62061. /**
  62062. * @hidden Internal global position in the SPS.
  62063. */
  62064. this._globalPosition = BABYLON.Vector3.Zero();
  62065. this.idx = particleIndex;
  62066. this._pos = positionIndex;
  62067. this._ind = indiceIndex;
  62068. this._model = model;
  62069. this.shapeId = shapeId;
  62070. this.idxInShape = idxInShape;
  62071. this._sps = sps;
  62072. if (modelBoundingInfo) {
  62073. this._modelBoundingInfo = modelBoundingInfo;
  62074. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  62075. }
  62076. }
  62077. Object.defineProperty(SolidParticle.prototype, "scale", {
  62078. /**
  62079. * Legacy support, changed scale to scaling
  62080. */
  62081. get: function () {
  62082. return this.scaling;
  62083. },
  62084. /**
  62085. * Legacy support, changed scale to scaling
  62086. */
  62087. set: function (scale) {
  62088. this.scaling = scale;
  62089. },
  62090. enumerable: true,
  62091. configurable: true
  62092. });
  62093. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  62094. /**
  62095. * Legacy support, changed quaternion to rotationQuaternion
  62096. */
  62097. get: function () {
  62098. return this.rotationQuaternion;
  62099. },
  62100. /**
  62101. * Legacy support, changed quaternion to rotationQuaternion
  62102. */
  62103. set: function (q) {
  62104. this.rotationQuaternion = q;
  62105. },
  62106. enumerable: true,
  62107. configurable: true
  62108. });
  62109. /**
  62110. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  62111. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  62112. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  62113. * @returns true if it intersects
  62114. */
  62115. SolidParticle.prototype.intersectsMesh = function (target) {
  62116. if (!this._boundingInfo || !target._boundingInfo) {
  62117. return false;
  62118. }
  62119. if (this._sps._bSphereOnly) {
  62120. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  62121. }
  62122. return this._boundingInfo.intersects(target._boundingInfo, false);
  62123. };
  62124. return SolidParticle;
  62125. }());
  62126. BABYLON.SolidParticle = SolidParticle;
  62127. /**
  62128. * Represents the shape of the model used by one particle of a solid particle system.
  62129. * SPS internal tool, don't use it manually.
  62130. */
  62131. var ModelShape = /** @class */ (function () {
  62132. /**
  62133. * 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.
  62134. * SPS internal tool, don't use it manually.
  62135. * @hidden
  62136. */
  62137. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  62138. /**
  62139. * length of the shape in the model indices array (internal use)
  62140. * @hidden
  62141. */
  62142. this._indicesLength = 0;
  62143. this.shapeID = id;
  62144. this._shape = shape;
  62145. this._indicesLength = indicesLength;
  62146. this._shapeUV = shapeUV;
  62147. this._positionFunction = posFunction;
  62148. this._vertexFunction = vtxFunction;
  62149. }
  62150. return ModelShape;
  62151. }());
  62152. BABYLON.ModelShape = ModelShape;
  62153. /**
  62154. * Represents a Depth Sorted Particle in the solid particle system.
  62155. */
  62156. var DepthSortedParticle = /** @class */ (function () {
  62157. function DepthSortedParticle() {
  62158. /**
  62159. * Index of the particle in the "indices" array
  62160. */
  62161. this.ind = 0;
  62162. /**
  62163. * Length of the particle shape in the "indices" array
  62164. */
  62165. this.indicesLength = 0;
  62166. /**
  62167. * Squared distance from the particle to the camera
  62168. */
  62169. this.sqDistance = 0.0;
  62170. }
  62171. return DepthSortedParticle;
  62172. }());
  62173. BABYLON.DepthSortedParticle = DepthSortedParticle;
  62174. })(BABYLON || (BABYLON = {}));
  62175. //# sourceMappingURL=babylon.solidParticle.js.map
  62176. var BABYLON;
  62177. (function (BABYLON) {
  62178. /**
  62179. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  62180. *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.
  62181. * The SPS is also a particle system. It provides some methods to manage the particles.
  62182. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  62183. *
  62184. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  62185. */
  62186. var SolidParticleSystem = /** @class */ (function () {
  62187. /**
  62188. * Creates a SPS (Solid Particle System) object.
  62189. * @param name (String) is the SPS name, this will be the underlying mesh name.
  62190. * @param scene (Scene) is the scene in which the SPS is added.
  62191. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  62192. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  62193. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  62194. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  62195. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  62196. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  62197. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  62198. */
  62199. function SolidParticleSystem(name, scene, options) {
  62200. /**
  62201. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  62202. * Example : var p = SPS.particles[i];
  62203. */
  62204. this.particles = new Array();
  62205. /**
  62206. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  62207. */
  62208. this.nbParticles = 0;
  62209. /**
  62210. * If the particles must ever face the camera (default false). Useful for planar particles.
  62211. */
  62212. this.billboard = false;
  62213. /**
  62214. * Recompute normals when adding a shape
  62215. */
  62216. this.recomputeNormals = true;
  62217. /**
  62218. * This a counter ofr your own usage. It's not set by any SPS functions.
  62219. */
  62220. this.counter = 0;
  62221. /**
  62222. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  62223. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  62224. */
  62225. this.vars = {};
  62226. /**
  62227. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  62228. * @hidden
  62229. */
  62230. this._bSphereOnly = false;
  62231. /**
  62232. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  62233. * @hidden
  62234. */
  62235. this._bSphereRadiusFactor = 1.0;
  62236. this._positions = new Array();
  62237. this._indices = new Array();
  62238. this._normals = new Array();
  62239. this._colors = new Array();
  62240. this._uvs = new Array();
  62241. this._index = 0; // indices index
  62242. this._updatable = true;
  62243. this._pickable = false;
  62244. this._isVisibilityBoxLocked = false;
  62245. this._alwaysVisible = false;
  62246. this._depthSort = false;
  62247. this._shapeCounter = 0;
  62248. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  62249. this._color = new BABYLON.Color4(0, 0, 0, 0);
  62250. this._computeParticleColor = true;
  62251. this._computeParticleTexture = true;
  62252. this._computeParticleRotation = true;
  62253. this._computeParticleVertex = false;
  62254. this._computeBoundingBox = false;
  62255. this._depthSortParticles = true;
  62256. this._cam_axisZ = BABYLON.Vector3.Zero();
  62257. this._cam_axisY = BABYLON.Vector3.Zero();
  62258. this._cam_axisX = BABYLON.Vector3.Zero();
  62259. this._axisZ = BABYLON.Axis.Z;
  62260. this._camDir = BABYLON.Vector3.Zero();
  62261. this._camInvertedPosition = BABYLON.Vector3.Zero();
  62262. this._rotMatrix = new BABYLON.Matrix();
  62263. this._invertMatrix = new BABYLON.Matrix();
  62264. this._rotated = BABYLON.Vector3.Zero();
  62265. this._quaternion = new BABYLON.Quaternion();
  62266. this._vertex = BABYLON.Vector3.Zero();
  62267. this._normal = BABYLON.Vector3.Zero();
  62268. this._yaw = 0.0;
  62269. this._pitch = 0.0;
  62270. this._roll = 0.0;
  62271. this._halfroll = 0.0;
  62272. this._halfpitch = 0.0;
  62273. this._halfyaw = 0.0;
  62274. this._sinRoll = 0.0;
  62275. this._cosRoll = 0.0;
  62276. this._sinPitch = 0.0;
  62277. this._cosPitch = 0.0;
  62278. this._sinYaw = 0.0;
  62279. this._cosYaw = 0.0;
  62280. this._mustUnrotateFixedNormals = false;
  62281. this._minimum = BABYLON.Vector3.Zero();
  62282. this._maximum = BABYLON.Vector3.Zero();
  62283. this._minBbox = BABYLON.Vector3.Zero();
  62284. this._maxBbox = BABYLON.Vector3.Zero();
  62285. this._particlesIntersect = false;
  62286. this._depthSortFunction = function (p1, p2) {
  62287. return (p2.sqDistance - p1.sqDistance);
  62288. };
  62289. this._needs32Bits = false;
  62290. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  62291. this._scaledPivot = BABYLON.Vector3.Zero();
  62292. this._particleHasParent = false;
  62293. this.name = name;
  62294. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62295. this._camera = scene.activeCamera;
  62296. this._pickable = options ? options.isPickable : false;
  62297. this._depthSort = options ? options.enableDepthSort : false;
  62298. this._particlesIntersect = options ? options.particleIntersection : false;
  62299. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  62300. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  62301. if (options && options.updatable !== undefined) {
  62302. this._updatable = options.updatable;
  62303. }
  62304. else {
  62305. this._updatable = true;
  62306. }
  62307. if (this._pickable) {
  62308. this.pickedParticles = [];
  62309. }
  62310. if (this._depthSort) {
  62311. this.depthSortedParticles = [];
  62312. }
  62313. }
  62314. /**
  62315. * Builds the SPS underlying mesh. Returns a standard Mesh.
  62316. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  62317. * @returns the created mesh
  62318. */
  62319. SolidParticleSystem.prototype.buildMesh = function () {
  62320. if (this.nbParticles === 0) {
  62321. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  62322. this.addShape(triangle, 1);
  62323. triangle.dispose();
  62324. }
  62325. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  62326. this._positions32 = new Float32Array(this._positions);
  62327. this._uvs32 = new Float32Array(this._uvs);
  62328. this._colors32 = new Float32Array(this._colors);
  62329. if (this.recomputeNormals) {
  62330. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  62331. }
  62332. this._normals32 = new Float32Array(this._normals);
  62333. this._fixedNormal32 = new Float32Array(this._normals);
  62334. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  62335. this._unrotateFixedNormals();
  62336. }
  62337. var vertexData = new BABYLON.VertexData();
  62338. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  62339. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  62340. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  62341. if (this._uvs32.length > 0) {
  62342. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  62343. }
  62344. if (this._colors32.length > 0) {
  62345. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  62346. }
  62347. var mesh = new BABYLON.Mesh(this.name, this._scene);
  62348. vertexData.applyToMesh(mesh, this._updatable);
  62349. this.mesh = mesh;
  62350. this.mesh.isPickable = this._pickable;
  62351. // free memory
  62352. if (!this._depthSort) {
  62353. this._indices = null;
  62354. }
  62355. this._positions = null;
  62356. this._normals = null;
  62357. this._uvs = null;
  62358. this._colors = null;
  62359. if (!this._updatable) {
  62360. this.particles.length = 0;
  62361. }
  62362. return mesh;
  62363. };
  62364. /**
  62365. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  62366. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  62367. * Thus the particles generated from `digest()` have their property `position` set yet.
  62368. * @param mesh ( Mesh ) is the mesh to be digested
  62369. * @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
  62370. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  62371. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  62372. * @returns the current SPS
  62373. */
  62374. SolidParticleSystem.prototype.digest = function (mesh, options) {
  62375. var size = (options && options.facetNb) || 1;
  62376. var number = (options && options.number) || 0;
  62377. var delta = (options && options.delta) || 0;
  62378. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62379. var meshInd = mesh.getIndices();
  62380. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62381. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62382. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62383. var f = 0; // facet counter
  62384. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  62385. // compute size from number
  62386. if (number) {
  62387. number = (number > totalFacets) ? totalFacets : number;
  62388. size = Math.round(totalFacets / number);
  62389. delta = 0;
  62390. }
  62391. else {
  62392. size = (size > totalFacets) ? totalFacets : size;
  62393. }
  62394. var facetPos = []; // submesh positions
  62395. var facetInd = []; // submesh indices
  62396. var facetUV = []; // submesh UV
  62397. var facetCol = []; // submesh colors
  62398. var barycenter = BABYLON.Vector3.Zero();
  62399. var sizeO = size;
  62400. while (f < totalFacets) {
  62401. size = sizeO + Math.floor((1 + delta) * Math.random());
  62402. if (f > totalFacets - size) {
  62403. size = totalFacets - f;
  62404. }
  62405. // reset temp arrays
  62406. facetPos.length = 0;
  62407. facetInd.length = 0;
  62408. facetUV.length = 0;
  62409. facetCol.length = 0;
  62410. // iterate over "size" facets
  62411. var fi = 0;
  62412. for (var j = f * 3; j < (f + size) * 3; j++) {
  62413. facetInd.push(fi);
  62414. var i = meshInd[j];
  62415. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  62416. if (meshUV) {
  62417. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  62418. }
  62419. if (meshCol) {
  62420. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  62421. }
  62422. fi++;
  62423. }
  62424. // create a model shape for each single particle
  62425. var idx = this.nbParticles;
  62426. var shape = this._posToShape(facetPos);
  62427. var shapeUV = this._uvsToShapeUV(facetUV);
  62428. // compute the barycenter of the shape
  62429. var v;
  62430. for (v = 0; v < shape.length; v++) {
  62431. barycenter.addInPlace(shape[v]);
  62432. }
  62433. barycenter.scaleInPlace(1 / shape.length);
  62434. // shift the shape from its barycenter to the origin
  62435. for (v = 0; v < shape.length; v++) {
  62436. shape[v].subtractInPlace(barycenter);
  62437. }
  62438. var bInfo;
  62439. if (this._particlesIntersect) {
  62440. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  62441. }
  62442. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  62443. // add the particle in the SPS
  62444. var currentPos = this._positions.length;
  62445. var currentInd = this._indices.length;
  62446. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  62447. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  62448. // initialize the particle position
  62449. this.particles[this.nbParticles].position.addInPlace(barycenter);
  62450. this._index += shape.length;
  62451. idx++;
  62452. this.nbParticles++;
  62453. this._shapeCounter++;
  62454. f += size;
  62455. }
  62456. return this;
  62457. };
  62458. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  62459. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  62460. var index = 0;
  62461. var idx = 0;
  62462. for (var p = 0; p < this.particles.length; p++) {
  62463. this._particle = this.particles[p];
  62464. this._shape = this._particle._model._shape;
  62465. if (this._particle.rotationQuaternion) {
  62466. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  62467. }
  62468. else {
  62469. this._yaw = this._particle.rotation.y;
  62470. this._pitch = this._particle.rotation.x;
  62471. this._roll = this._particle.rotation.z;
  62472. this._quaternionRotationYPR();
  62473. }
  62474. this._quaternionToRotationMatrix();
  62475. this._rotMatrix.invertToRef(this._invertMatrix);
  62476. for (var pt = 0; pt < this._shape.length; pt++) {
  62477. idx = index + pt * 3;
  62478. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  62479. this._fixedNormal32[idx] = this._normal.x;
  62480. this._fixedNormal32[idx + 1] = this._normal.y;
  62481. this._fixedNormal32[idx + 2] = this._normal.z;
  62482. }
  62483. index = idx + 3;
  62484. }
  62485. };
  62486. //reset copy
  62487. SolidParticleSystem.prototype._resetCopy = function () {
  62488. this._copy.position.x = 0;
  62489. this._copy.position.y = 0;
  62490. this._copy.position.z = 0;
  62491. this._copy.rotation.x = 0;
  62492. this._copy.rotation.y = 0;
  62493. this._copy.rotation.z = 0;
  62494. this._copy.rotationQuaternion = null;
  62495. this._copy.scaling.x = 1.0;
  62496. this._copy.scaling.y = 1.0;
  62497. this._copy.scaling.z = 1.0;
  62498. this._copy.uvs.x = 0;
  62499. this._copy.uvs.y = 0;
  62500. this._copy.uvs.z = 1.0;
  62501. this._copy.uvs.w = 1.0;
  62502. this._copy.color = null;
  62503. this._copy.translateFromPivot = false;
  62504. };
  62505. // _meshBuilder : inserts the shape model in the global SPS mesh
  62506. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  62507. var i;
  62508. var u = 0;
  62509. var c = 0;
  62510. var n = 0;
  62511. this._resetCopy();
  62512. if (options && options.positionFunction) { // call to custom positionFunction
  62513. options.positionFunction(this._copy, idx, idxInShape);
  62514. this._mustUnrotateFixedNormals = true;
  62515. }
  62516. if (this._copy.rotationQuaternion) {
  62517. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  62518. }
  62519. else {
  62520. this._yaw = this._copy.rotation.y;
  62521. this._pitch = this._copy.rotation.x;
  62522. this._roll = this._copy.rotation.z;
  62523. this._quaternionRotationYPR();
  62524. }
  62525. this._quaternionToRotationMatrix();
  62526. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  62527. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  62528. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  62529. if (this._copy.translateFromPivot) {
  62530. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  62531. }
  62532. else {
  62533. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  62534. }
  62535. for (i = 0; i < shape.length; i++) {
  62536. this._vertex.x = shape[i].x;
  62537. this._vertex.y = shape[i].y;
  62538. this._vertex.z = shape[i].z;
  62539. if (options && options.vertexFunction) {
  62540. options.vertexFunction(this._copy, this._vertex, i);
  62541. }
  62542. this._vertex.x *= this._copy.scaling.x;
  62543. this._vertex.y *= this._copy.scaling.y;
  62544. this._vertex.z *= this._copy.scaling.z;
  62545. this._vertex.x -= this._scaledPivot.x;
  62546. this._vertex.y -= this._scaledPivot.y;
  62547. this._vertex.z -= this._scaledPivot.z;
  62548. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  62549. this._rotated.addInPlace(this._pivotBackTranslation);
  62550. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  62551. if (meshUV) {
  62552. 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);
  62553. u += 2;
  62554. }
  62555. if (this._copy.color) {
  62556. this._color = this._copy.color;
  62557. }
  62558. else if (meshCol && meshCol[c] !== undefined) {
  62559. this._color.r = meshCol[c];
  62560. this._color.g = meshCol[c + 1];
  62561. this._color.b = meshCol[c + 2];
  62562. this._color.a = meshCol[c + 3];
  62563. }
  62564. else {
  62565. this._color.r = 1.0;
  62566. this._color.g = 1.0;
  62567. this._color.b = 1.0;
  62568. this._color.a = 1.0;
  62569. }
  62570. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  62571. c += 4;
  62572. if (!this.recomputeNormals && meshNor) {
  62573. this._normal.x = meshNor[n];
  62574. this._normal.y = meshNor[n + 1];
  62575. this._normal.z = meshNor[n + 2];
  62576. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  62577. normals.push(this._normal.x, this._normal.y, this._normal.z);
  62578. n += 3;
  62579. }
  62580. }
  62581. for (i = 0; i < meshInd.length; i++) {
  62582. var current_ind = p + meshInd[i];
  62583. indices.push(current_ind);
  62584. if (current_ind > 65535) {
  62585. this._needs32Bits = true;
  62586. }
  62587. }
  62588. if (this._pickable) {
  62589. var nbfaces = meshInd.length / 3;
  62590. for (i = 0; i < nbfaces; i++) {
  62591. this.pickedParticles.push({ idx: idx, faceId: i });
  62592. }
  62593. }
  62594. if (this._depthSort) {
  62595. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  62596. }
  62597. return this._copy;
  62598. };
  62599. // returns a shape array from positions array
  62600. SolidParticleSystem.prototype._posToShape = function (positions) {
  62601. var shape = [];
  62602. for (var i = 0; i < positions.length; i += 3) {
  62603. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  62604. }
  62605. return shape;
  62606. };
  62607. // returns a shapeUV array from a Vector4 uvs
  62608. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  62609. var shapeUV = [];
  62610. if (uvs) {
  62611. for (var i = 0; i < uvs.length; i++)
  62612. shapeUV.push(uvs[i]);
  62613. }
  62614. return shapeUV;
  62615. };
  62616. // adds a new particle object in the particles array
  62617. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  62618. if (bInfo === void 0) { bInfo = null; }
  62619. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  62620. this.particles.push(sp);
  62621. return sp;
  62622. };
  62623. /**
  62624. * Adds some particles to the SPS from the model shape. Returns the shape id.
  62625. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  62626. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  62627. * @param nb (positive integer) the number of particles to be created from this model
  62628. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  62629. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  62630. * @returns the number of shapes in the system
  62631. */
  62632. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  62633. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62634. var meshInd = mesh.getIndices();
  62635. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62636. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62637. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62638. var bbInfo;
  62639. if (this._particlesIntersect) {
  62640. bbInfo = mesh.getBoundingInfo();
  62641. }
  62642. var shape = this._posToShape(meshPos);
  62643. var shapeUV = this._uvsToShapeUV(meshUV);
  62644. var posfunc = options ? options.positionFunction : null;
  62645. var vtxfunc = options ? options.vertexFunction : null;
  62646. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  62647. // particles
  62648. var sp;
  62649. var currentCopy;
  62650. var idx = this.nbParticles;
  62651. for (var i = 0; i < nb; i++) {
  62652. var currentPos = this._positions.length;
  62653. var currentInd = this._indices.length;
  62654. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  62655. if (this._updatable) {
  62656. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  62657. sp.position.copyFrom(currentCopy.position);
  62658. sp.rotation.copyFrom(currentCopy.rotation);
  62659. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  62660. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  62661. }
  62662. if (currentCopy.color && sp.color) {
  62663. sp.color.copyFrom(currentCopy.color);
  62664. }
  62665. sp.scaling.copyFrom(currentCopy.scaling);
  62666. sp.uvs.copyFrom(currentCopy.uvs);
  62667. }
  62668. this._index += shape.length;
  62669. idx++;
  62670. }
  62671. this.nbParticles += nb;
  62672. this._shapeCounter++;
  62673. return this._shapeCounter - 1;
  62674. };
  62675. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  62676. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  62677. this._resetCopy();
  62678. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  62679. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  62680. }
  62681. if (this._copy.rotationQuaternion) {
  62682. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  62683. }
  62684. else {
  62685. this._yaw = this._copy.rotation.y;
  62686. this._pitch = this._copy.rotation.x;
  62687. this._roll = this._copy.rotation.z;
  62688. this._quaternionRotationYPR();
  62689. }
  62690. this._quaternionToRotationMatrix();
  62691. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  62692. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  62693. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  62694. if (this._copy.translateFromPivot) {
  62695. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  62696. }
  62697. else {
  62698. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  62699. }
  62700. this._shape = particle._model._shape;
  62701. for (var pt = 0; pt < this._shape.length; pt++) {
  62702. this._vertex.x = this._shape[pt].x;
  62703. this._vertex.y = this._shape[pt].y;
  62704. this._vertex.z = this._shape[pt].z;
  62705. if (particle._model._vertexFunction) {
  62706. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  62707. }
  62708. this._vertex.x *= this._copy.scaling.x;
  62709. this._vertex.y *= this._copy.scaling.y;
  62710. this._vertex.z *= this._copy.scaling.z;
  62711. this._vertex.x -= this._scaledPivot.x;
  62712. this._vertex.y -= this._scaledPivot.y;
  62713. this._vertex.z -= this._scaledPivot.z;
  62714. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  62715. this._rotated.addInPlace(this._pivotBackTranslation);
  62716. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  62717. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  62718. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  62719. }
  62720. particle.position.x = 0.0;
  62721. particle.position.y = 0.0;
  62722. particle.position.z = 0.0;
  62723. particle.rotation.x = 0.0;
  62724. particle.rotation.y = 0.0;
  62725. particle.rotation.z = 0.0;
  62726. particle.rotationQuaternion = null;
  62727. particle.scaling.x = 1.0;
  62728. particle.scaling.y = 1.0;
  62729. particle.scaling.z = 1.0;
  62730. particle.uvs.x = 0.0;
  62731. particle.uvs.y = 0.0;
  62732. particle.uvs.z = 1.0;
  62733. particle.uvs.w = 1.0;
  62734. particle.pivot.x = 0.0;
  62735. particle.pivot.y = 0.0;
  62736. particle.pivot.z = 0.0;
  62737. particle.translateFromPivot = false;
  62738. particle.parentId = null;
  62739. };
  62740. /**
  62741. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  62742. * @returns the SPS.
  62743. */
  62744. SolidParticleSystem.prototype.rebuildMesh = function () {
  62745. for (var p = 0; p < this.particles.length; p++) {
  62746. this._rebuildParticle(this.particles[p]);
  62747. }
  62748. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  62749. return this;
  62750. };
  62751. /**
  62752. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  62753. * This method calls `updateParticle()` for each particle of the SPS.
  62754. * For an animated SPS, it is usually called within the render loop.
  62755. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  62756. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  62757. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  62758. * @returns the SPS.
  62759. */
  62760. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  62761. if (start === void 0) { start = 0; }
  62762. if (end === void 0) { end = this.nbParticles - 1; }
  62763. if (update === void 0) { update = true; }
  62764. if (!this._updatable) {
  62765. return this;
  62766. }
  62767. // custom beforeUpdate
  62768. this.beforeUpdateParticles(start, end, update);
  62769. this._cam_axisX.x = 1.0;
  62770. this._cam_axisX.y = 0.0;
  62771. this._cam_axisX.z = 0.0;
  62772. this._cam_axisY.x = 0.0;
  62773. this._cam_axisY.y = 1.0;
  62774. this._cam_axisY.z = 0.0;
  62775. this._cam_axisZ.x = 0.0;
  62776. this._cam_axisZ.y = 0.0;
  62777. this._cam_axisZ.z = 1.0;
  62778. // cases when the World Matrix is to be computed first
  62779. if (this.billboard || this._depthSort) {
  62780. this.mesh.computeWorldMatrix(true);
  62781. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  62782. }
  62783. // if the particles will always face the camera
  62784. if (this.billboard) {
  62785. // compute the camera position and un-rotate it by the current mesh rotation
  62786. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  62787. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  62788. this._cam_axisZ.normalize();
  62789. // same for camera up vector extracted from the cam view matrix
  62790. var view = this._camera.getViewMatrix(true);
  62791. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  62792. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  62793. this._cam_axisY.normalize();
  62794. this._cam_axisX.normalize();
  62795. }
  62796. // if depthSort, compute the camera global position in the mesh local system
  62797. if (this._depthSort) {
  62798. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  62799. }
  62800. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  62801. var idx = 0; // current position index in the global array positions32
  62802. var index = 0; // position start index in the global array positions32 of the current particle
  62803. var colidx = 0; // current color index in the global array colors32
  62804. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  62805. var uvidx = 0; // current uv index in the global array uvs32
  62806. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  62807. var pt = 0; // current index in the particle model shape
  62808. if (this.mesh.isFacetDataEnabled) {
  62809. this._computeBoundingBox = true;
  62810. }
  62811. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  62812. if (this._computeBoundingBox) {
  62813. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  62814. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  62815. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  62816. }
  62817. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  62818. if (this.mesh._boundingInfo) {
  62819. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  62820. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  62821. }
  62822. }
  62823. }
  62824. // particle loop
  62825. index = this.particles[start]._pos;
  62826. var vpos = (index / 3) | 0;
  62827. colorIndex = vpos * 4;
  62828. uvIndex = vpos * 2;
  62829. for (var p = start; p <= end; p++) {
  62830. this._particle = this.particles[p];
  62831. this._shape = this._particle._model._shape;
  62832. this._shapeUV = this._particle._model._shapeUV;
  62833. // call to custom user function to update the particle properties
  62834. this.updateParticle(this._particle);
  62835. // camera-particle distance for depth sorting
  62836. if (this._depthSort && this._depthSortParticles) {
  62837. var dsp = this.depthSortedParticles[p];
  62838. dsp.ind = this._particle._ind;
  62839. dsp.indicesLength = this._particle._model._indicesLength;
  62840. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  62841. }
  62842. // skip the computations for inactive or already invisible particles
  62843. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  62844. // increment indexes for the next particle
  62845. pt = this._shape.length;
  62846. index += pt * 3;
  62847. colorIndex += pt * 4;
  62848. uvIndex += pt * 2;
  62849. continue;
  62850. }
  62851. if (this._particle.isVisible) {
  62852. this._particle._stillInvisible = false; // un-mark permanent invisibility
  62853. this._particleHasParent = (this._particle.parentId !== null);
  62854. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  62855. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  62856. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  62857. // particle rotation matrix
  62858. if (this.billboard) {
  62859. this._particle.rotation.x = 0.0;
  62860. this._particle.rotation.y = 0.0;
  62861. }
  62862. if (this._computeParticleRotation || this.billboard) {
  62863. if (this._particle.rotationQuaternion) {
  62864. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  62865. }
  62866. else {
  62867. this._yaw = this._particle.rotation.y;
  62868. this._pitch = this._particle.rotation.x;
  62869. this._roll = this._particle.rotation.z;
  62870. this._quaternionRotationYPR();
  62871. }
  62872. this._quaternionToRotationMatrix();
  62873. }
  62874. if (this._particleHasParent) {
  62875. this._parent = this.particles[this._particle.parentId];
  62876. 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];
  62877. 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];
  62878. 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];
  62879. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  62880. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  62881. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  62882. if (this._computeParticleRotation || this.billboard) {
  62883. 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];
  62884. 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];
  62885. 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];
  62886. 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];
  62887. 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];
  62888. 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];
  62889. 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];
  62890. 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];
  62891. 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];
  62892. }
  62893. }
  62894. else {
  62895. this._particle._globalPosition.x = this._particle.position.x;
  62896. this._particle._globalPosition.y = this._particle.position.y;
  62897. this._particle._globalPosition.z = this._particle.position.z;
  62898. if (this._computeParticleRotation || this.billboard) {
  62899. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  62900. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  62901. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  62902. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  62903. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  62904. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  62905. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  62906. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  62907. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  62908. }
  62909. }
  62910. if (this._particle.translateFromPivot) {
  62911. this._pivotBackTranslation.x = 0.0;
  62912. this._pivotBackTranslation.y = 0.0;
  62913. this._pivotBackTranslation.z = 0.0;
  62914. }
  62915. else {
  62916. this._pivotBackTranslation.x = this._scaledPivot.x;
  62917. this._pivotBackTranslation.y = this._scaledPivot.y;
  62918. this._pivotBackTranslation.z = this._scaledPivot.z;
  62919. }
  62920. // particle vertex loop
  62921. for (pt = 0; pt < this._shape.length; pt++) {
  62922. idx = index + pt * 3;
  62923. colidx = colorIndex + pt * 4;
  62924. uvidx = uvIndex + pt * 2;
  62925. this._vertex.x = this._shape[pt].x;
  62926. this._vertex.y = this._shape[pt].y;
  62927. this._vertex.z = this._shape[pt].z;
  62928. if (this._computeParticleVertex) {
  62929. this.updateParticleVertex(this._particle, this._vertex, pt);
  62930. }
  62931. // positions
  62932. this._vertex.x *= this._particle.scaling.x;
  62933. this._vertex.y *= this._particle.scaling.y;
  62934. this._vertex.z *= this._particle.scaling.z;
  62935. this._vertex.x -= this._scaledPivot.x;
  62936. this._vertex.y -= this._scaledPivot.y;
  62937. this._vertex.z -= this._scaledPivot.z;
  62938. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  62939. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  62940. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  62941. this._rotated.x += this._pivotBackTranslation.x;
  62942. this._rotated.y += this._pivotBackTranslation.y;
  62943. this._rotated.z += this._pivotBackTranslation.z;
  62944. 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;
  62945. 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;
  62946. 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;
  62947. if (this._computeBoundingBox) {
  62948. if (this._positions32[idx] < this._minimum.x) {
  62949. this._minimum.x = this._positions32[idx];
  62950. }
  62951. if (this._positions32[idx] > this._maximum.x) {
  62952. this._maximum.x = this._positions32[idx];
  62953. }
  62954. if (this._positions32[idx + 1] < this._minimum.y) {
  62955. this._minimum.y = this._positions32[idx + 1];
  62956. }
  62957. if (this._positions32[idx + 1] > this._maximum.y) {
  62958. this._maximum.y = this._positions32[idx + 1];
  62959. }
  62960. if (this._positions32[idx + 2] < this._minimum.z) {
  62961. this._minimum.z = this._positions32[idx + 2];
  62962. }
  62963. if (this._positions32[idx + 2] > this._maximum.z) {
  62964. this._maximum.z = this._positions32[idx + 2];
  62965. }
  62966. }
  62967. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  62968. if (!this._computeParticleVertex) {
  62969. this._normal.x = this._fixedNormal32[idx];
  62970. this._normal.y = this._fixedNormal32[idx + 1];
  62971. this._normal.z = this._fixedNormal32[idx + 2];
  62972. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  62973. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  62974. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  62975. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  62976. 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;
  62977. 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;
  62978. }
  62979. if (this._computeParticleColor && this._particle.color) {
  62980. this._colors32[colidx] = this._particle.color.r;
  62981. this._colors32[colidx + 1] = this._particle.color.g;
  62982. this._colors32[colidx + 2] = this._particle.color.b;
  62983. this._colors32[colidx + 3] = this._particle.color.a;
  62984. }
  62985. if (this._computeParticleTexture) {
  62986. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  62987. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  62988. }
  62989. }
  62990. }
  62991. // particle just set invisible : scaled to zero and positioned at the origin
  62992. else {
  62993. this._particle._stillInvisible = true; // mark the particle as invisible
  62994. for (pt = 0; pt < this._shape.length; pt++) {
  62995. idx = index + pt * 3;
  62996. colidx = colorIndex + pt * 4;
  62997. uvidx = uvIndex + pt * 2;
  62998. this._positions32[idx] = 0.0;
  62999. this._positions32[idx + 1] = 0.0;
  63000. this._positions32[idx + 2] = 0.0;
  63001. this._normals32[idx] = 0.0;
  63002. this._normals32[idx + 1] = 0.0;
  63003. this._normals32[idx + 2] = 0.0;
  63004. if (this._computeParticleColor && this._particle.color) {
  63005. this._colors32[colidx] = this._particle.color.r;
  63006. this._colors32[colidx + 1] = this._particle.color.g;
  63007. this._colors32[colidx + 2] = this._particle.color.b;
  63008. this._colors32[colidx + 3] = this._particle.color.a;
  63009. }
  63010. if (this._computeParticleTexture) {
  63011. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  63012. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  63013. }
  63014. }
  63015. }
  63016. // if the particle intersections must be computed : update the bbInfo
  63017. if (this._particlesIntersect) {
  63018. var bInfo = this._particle._boundingInfo;
  63019. var bBox = bInfo.boundingBox;
  63020. var bSphere = bInfo.boundingSphere;
  63021. if (!this._bSphereOnly) {
  63022. // place, scale and rotate the particle bbox within the SPS local system, then update it
  63023. for (var b = 0; b < bBox.vectors.length; b++) {
  63024. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  63025. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  63026. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  63027. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  63028. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  63029. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  63030. 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;
  63031. 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;
  63032. 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;
  63033. }
  63034. bBox._update(this.mesh._worldMatrix);
  63035. }
  63036. // place and scale the particle bouding sphere in the SPS local system, then update it
  63037. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  63038. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  63039. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  63040. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  63041. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  63042. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  63043. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  63044. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  63045. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  63046. 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));
  63047. bSphere._update(this.mesh._worldMatrix);
  63048. }
  63049. // increment indexes for the next particle
  63050. index = idx + 3;
  63051. colorIndex = colidx + 4;
  63052. uvIndex = uvidx + 2;
  63053. }
  63054. // if the VBO must be updated
  63055. if (update) {
  63056. if (this._computeParticleColor) {
  63057. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  63058. }
  63059. if (this._computeParticleTexture) {
  63060. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  63061. }
  63062. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  63063. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  63064. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  63065. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  63066. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  63067. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  63068. for (var i = 0; i < this._normals32.length; i++) {
  63069. this._fixedNormal32[i] = this._normals32[i];
  63070. }
  63071. }
  63072. if (!this.mesh.areNormalsFrozen) {
  63073. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  63074. }
  63075. }
  63076. if (this._depthSort && this._depthSortParticles) {
  63077. this.depthSortedParticles.sort(this._depthSortFunction);
  63078. var dspl = this.depthSortedParticles.length;
  63079. var sorted = 0;
  63080. var lind = 0;
  63081. var sind = 0;
  63082. var sid = 0;
  63083. for (sorted = 0; sorted < dspl; sorted++) {
  63084. lind = this.depthSortedParticles[sorted].indicesLength;
  63085. sind = this.depthSortedParticles[sorted].ind;
  63086. for (var i = 0; i < lind; i++) {
  63087. this._indices32[sid] = this._indices[sind + i];
  63088. sid++;
  63089. }
  63090. }
  63091. this.mesh.updateIndices(this._indices32);
  63092. }
  63093. }
  63094. if (this._computeBoundingBox) {
  63095. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  63096. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  63097. }
  63098. this.afterUpdateParticles(start, end, update);
  63099. return this;
  63100. };
  63101. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  63102. this._halfroll = this._roll * 0.5;
  63103. this._halfpitch = this._pitch * 0.5;
  63104. this._halfyaw = this._yaw * 0.5;
  63105. this._sinRoll = Math.sin(this._halfroll);
  63106. this._cosRoll = Math.cos(this._halfroll);
  63107. this._sinPitch = Math.sin(this._halfpitch);
  63108. this._cosPitch = Math.cos(this._halfpitch);
  63109. this._sinYaw = Math.sin(this._halfyaw);
  63110. this._cosYaw = Math.cos(this._halfyaw);
  63111. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  63112. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  63113. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  63114. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  63115. };
  63116. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  63117. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  63118. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  63119. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  63120. this._rotMatrix.m[3] = 0;
  63121. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  63122. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  63123. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  63124. this._rotMatrix.m[7] = 0;
  63125. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  63126. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  63127. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  63128. this._rotMatrix.m[11] = 0;
  63129. this._rotMatrix.m[12] = 0;
  63130. this._rotMatrix.m[13] = 0;
  63131. this._rotMatrix.m[14] = 0;
  63132. this._rotMatrix.m[15] = 1.0;
  63133. };
  63134. /**
  63135. * Disposes the SPS.
  63136. */
  63137. SolidParticleSystem.prototype.dispose = function () {
  63138. this.mesh.dispose();
  63139. this.vars = null;
  63140. // drop references to internal big arrays for the GC
  63141. this._positions = null;
  63142. this._indices = null;
  63143. this._normals = null;
  63144. this._uvs = null;
  63145. this._colors = null;
  63146. this._indices32 = null;
  63147. this._positions32 = null;
  63148. this._normals32 = null;
  63149. this._fixedNormal32 = null;
  63150. this._uvs32 = null;
  63151. this._colors32 = null;
  63152. this.pickedParticles = null;
  63153. };
  63154. /**
  63155. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  63156. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63157. * @returns the SPS.
  63158. */
  63159. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  63160. if (!this._isVisibilityBoxLocked) {
  63161. this.mesh.refreshBoundingInfo();
  63162. }
  63163. return this;
  63164. };
  63165. /**
  63166. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  63167. * @param size the size (float) of the visibility box
  63168. * note : this doesn't lock the SPS mesh bounding box.
  63169. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63170. */
  63171. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  63172. var vis = size / 2;
  63173. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  63174. };
  63175. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  63176. /**
  63177. * Gets whether the SPS as always visible or not
  63178. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63179. */
  63180. get: function () {
  63181. return this._alwaysVisible;
  63182. },
  63183. /**
  63184. * Sets the SPS as always visible or not
  63185. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63186. */
  63187. set: function (val) {
  63188. this._alwaysVisible = val;
  63189. this.mesh.alwaysSelectAsActiveMesh = val;
  63190. },
  63191. enumerable: true,
  63192. configurable: true
  63193. });
  63194. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  63195. /**
  63196. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  63197. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63198. */
  63199. get: function () {
  63200. return this._isVisibilityBoxLocked;
  63201. },
  63202. /**
  63203. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  63204. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63205. */
  63206. set: function (val) {
  63207. this._isVisibilityBoxLocked = val;
  63208. var boundingInfo = this.mesh.getBoundingInfo();
  63209. boundingInfo.isLocked = val;
  63210. },
  63211. enumerable: true,
  63212. configurable: true
  63213. });
  63214. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  63215. /**
  63216. * Gets if `setParticles()` computes the particle rotations or not.
  63217. * Default value : true. The SPS is faster when it's set to false.
  63218. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  63219. */
  63220. get: function () {
  63221. return this._computeParticleRotation;
  63222. },
  63223. /**
  63224. * Tells to `setParticles()` to compute the particle rotations or not.
  63225. * Default value : true. The SPS is faster when it's set to false.
  63226. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  63227. */
  63228. set: function (val) {
  63229. this._computeParticleRotation = val;
  63230. },
  63231. enumerable: true,
  63232. configurable: true
  63233. });
  63234. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  63235. /**
  63236. * Gets if `setParticles()` computes the particle colors or not.
  63237. * Default value : true. The SPS is faster when it's set to false.
  63238. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  63239. */
  63240. get: function () {
  63241. return this._computeParticleColor;
  63242. },
  63243. /**
  63244. * Tells to `setParticles()` to compute the particle colors or not.
  63245. * Default value : true. The SPS is faster when it's set to false.
  63246. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  63247. */
  63248. set: function (val) {
  63249. this._computeParticleColor = val;
  63250. },
  63251. enumerable: true,
  63252. configurable: true
  63253. });
  63254. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  63255. /**
  63256. * Gets if `setParticles()` computes the particle textures or not.
  63257. * Default value : true. The SPS is faster when it's set to false.
  63258. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  63259. */
  63260. get: function () {
  63261. return this._computeParticleTexture;
  63262. },
  63263. set: function (val) {
  63264. this._computeParticleTexture = val;
  63265. },
  63266. enumerable: true,
  63267. configurable: true
  63268. });
  63269. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  63270. /**
  63271. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  63272. * Default value : false. The SPS is faster when it's set to false.
  63273. * Note : the particle custom vertex positions aren't stored values.
  63274. */
  63275. get: function () {
  63276. return this._computeParticleVertex;
  63277. },
  63278. /**
  63279. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  63280. * Default value : false. The SPS is faster when it's set to false.
  63281. * Note : the particle custom vertex positions aren't stored values.
  63282. */
  63283. set: function (val) {
  63284. this._computeParticleVertex = val;
  63285. },
  63286. enumerable: true,
  63287. configurable: true
  63288. });
  63289. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  63290. /**
  63291. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  63292. */
  63293. get: function () {
  63294. return this._computeBoundingBox;
  63295. },
  63296. /**
  63297. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  63298. */
  63299. set: function (val) {
  63300. this._computeBoundingBox = val;
  63301. },
  63302. enumerable: true,
  63303. configurable: true
  63304. });
  63305. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  63306. /**
  63307. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  63308. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  63309. * Default : `true`
  63310. */
  63311. get: function () {
  63312. return this._depthSortParticles;
  63313. },
  63314. /**
  63315. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  63316. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  63317. * Default : `true`
  63318. */
  63319. set: function (val) {
  63320. this._depthSortParticles = val;
  63321. },
  63322. enumerable: true,
  63323. configurable: true
  63324. });
  63325. // =======================================================================
  63326. // Particle behavior logic
  63327. // these following methods may be overwritten by the user to fit his needs
  63328. /**
  63329. * This function does nothing. It may be overwritten to set all the particle first values.
  63330. * The SPS doesn't call this function, you may have to call it by your own.
  63331. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63332. */
  63333. SolidParticleSystem.prototype.initParticles = function () {
  63334. };
  63335. /**
  63336. * This function does nothing. It may be overwritten to recycle a particle.
  63337. * The SPS doesn't call this function, you may have to call it by your own.
  63338. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63339. * @param particle The particle to recycle
  63340. * @returns the recycled particle
  63341. */
  63342. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  63343. return particle;
  63344. };
  63345. /**
  63346. * Updates a particle : this function should be overwritten by the user.
  63347. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  63348. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63349. * @example : just set a particle position or velocity and recycle conditions
  63350. * @param particle The particle to update
  63351. * @returns the updated particle
  63352. */
  63353. SolidParticleSystem.prototype.updateParticle = function (particle) {
  63354. return particle;
  63355. };
  63356. /**
  63357. * Updates a vertex of a particle : it can be overwritten by the user.
  63358. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  63359. * @param particle the current particle
  63360. * @param vertex the current index of the current particle
  63361. * @param pt the index of the current vertex in the particle shape
  63362. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  63363. * @example : just set a vertex particle position
  63364. * @returns the updated vertex
  63365. */
  63366. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  63367. return vertex;
  63368. };
  63369. /**
  63370. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  63371. * This does nothing and may be overwritten by the user.
  63372. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63373. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63374. * @param update the boolean update value actually passed to setParticles()
  63375. */
  63376. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  63377. };
  63378. /**
  63379. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  63380. * This will be passed three parameters.
  63381. * This does nothing and may be overwritten by the user.
  63382. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63383. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63384. * @param update the boolean update value actually passed to setParticles()
  63385. */
  63386. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  63387. };
  63388. return SolidParticleSystem;
  63389. }());
  63390. BABYLON.SolidParticleSystem = SolidParticleSystem;
  63391. })(BABYLON || (BABYLON = {}));
  63392. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  63393. var BABYLON;
  63394. (function (BABYLON) {
  63395. /**
  63396. * Class containing static functions to help procedurally build meshes
  63397. */
  63398. var MeshBuilder = /** @class */ (function () {
  63399. function MeshBuilder() {
  63400. }
  63401. MeshBuilder.updateSideOrientation = function (orientation) {
  63402. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  63403. return BABYLON.Mesh.DOUBLESIDE;
  63404. }
  63405. if (orientation === undefined || orientation === null) {
  63406. return BABYLON.Mesh.FRONTSIDE;
  63407. }
  63408. return orientation;
  63409. };
  63410. /**
  63411. * Creates a box mesh
  63412. * * The parameter `size` sets the size (float) of each box side (default 1)
  63413. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  63414. * * 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)
  63415. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  63416. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63417. * * 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
  63418. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63419. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  63420. * @param name defines the name of the mesh
  63421. * @param options defines the options used to create the mesh
  63422. * @param scene defines the hosting scene
  63423. * @returns the box mesh
  63424. */
  63425. MeshBuilder.CreateBox = function (name, options, scene) {
  63426. if (scene === void 0) { scene = null; }
  63427. var box = new BABYLON.Mesh(name, scene);
  63428. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63429. box._originalBuilderSideOrientation = options.sideOrientation;
  63430. var vertexData = BABYLON.VertexData.CreateBox(options);
  63431. vertexData.applyToMesh(box, options.updatable);
  63432. return box;
  63433. };
  63434. /**
  63435. * Creates a sphere mesh
  63436. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  63437. * * 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`)
  63438. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  63439. * * 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
  63440. * * 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)
  63441. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63442. * * 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
  63443. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63444. * @param name defines the name of the mesh
  63445. * @param options defines the options used to create the mesh
  63446. * @param scene defines the hosting scene
  63447. * @returns the sphere mesh
  63448. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  63449. */
  63450. MeshBuilder.CreateSphere = function (name, options, scene) {
  63451. var sphere = new BABYLON.Mesh(name, scene);
  63452. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63453. sphere._originalBuilderSideOrientation = options.sideOrientation;
  63454. var vertexData = BABYLON.VertexData.CreateSphere(options);
  63455. vertexData.applyToMesh(sphere, options.updatable);
  63456. return sphere;
  63457. };
  63458. /**
  63459. * Creates a plane polygonal mesh. By default, this is a disc
  63460. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  63461. * * 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
  63462. * * 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
  63463. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63464. * * 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
  63465. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63466. * @param name defines the name of the mesh
  63467. * @param options defines the options used to create the mesh
  63468. * @param scene defines the hosting scene
  63469. * @returns the plane polygonal mesh
  63470. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  63471. */
  63472. MeshBuilder.CreateDisc = function (name, options, scene) {
  63473. if (scene === void 0) { scene = null; }
  63474. var disc = new BABYLON.Mesh(name, scene);
  63475. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63476. disc._originalBuilderSideOrientation = options.sideOrientation;
  63477. var vertexData = BABYLON.VertexData.CreateDisc(options);
  63478. vertexData.applyToMesh(disc, options.updatable);
  63479. return disc;
  63480. };
  63481. /**
  63482. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  63483. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  63484. * * 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`)
  63485. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  63486. * * 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
  63487. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63488. * * 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
  63489. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63490. * @param name defines the name of the mesh
  63491. * @param options defines the options used to create the mesh
  63492. * @param scene defines the hosting scene
  63493. * @returns the icosahedron mesh
  63494. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  63495. */
  63496. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  63497. var sphere = new BABYLON.Mesh(name, scene);
  63498. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63499. sphere._originalBuilderSideOrientation = options.sideOrientation;
  63500. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  63501. vertexData.applyToMesh(sphere, options.updatable);
  63502. return sphere;
  63503. };
  63504. ;
  63505. /**
  63506. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  63507. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  63508. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  63509. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  63510. * * 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
  63511. * * 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
  63512. * * 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
  63513. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63514. * * 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
  63515. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63516. * * 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
  63517. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  63518. * * 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
  63519. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  63520. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63521. * @param name defines the name of the mesh
  63522. * @param options defines the options used to create the mesh
  63523. * @param scene defines the hosting scene
  63524. * @returns the ribbon mesh
  63525. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  63526. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63527. */
  63528. MeshBuilder.CreateRibbon = function (name, options, scene) {
  63529. if (scene === void 0) { scene = null; }
  63530. var pathArray = options.pathArray;
  63531. var closeArray = options.closeArray;
  63532. var closePath = options.closePath;
  63533. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63534. var instance = options.instance;
  63535. var updatable = options.updatable;
  63536. if (instance) { // existing ribbon instance update
  63537. // positionFunction : ribbon case
  63538. // only pathArray and sideOrientation parameters are taken into account for positions update
  63539. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  63540. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  63541. var positionFunction = function (positions) {
  63542. var minlg = pathArray[0].length;
  63543. var i = 0;
  63544. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  63545. for (var si = 1; si <= ns; si++) {
  63546. for (var p = 0; p < pathArray.length; p++) {
  63547. var path = pathArray[p];
  63548. var l = path.length;
  63549. minlg = (minlg < l) ? minlg : l;
  63550. var j = 0;
  63551. while (j < minlg) {
  63552. positions[i] = path[j].x;
  63553. positions[i + 1] = path[j].y;
  63554. positions[i + 2] = path[j].z;
  63555. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  63556. BABYLON.Tmp.Vector3[0].x = path[j].x;
  63557. }
  63558. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  63559. BABYLON.Tmp.Vector3[1].x = path[j].x;
  63560. }
  63561. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  63562. BABYLON.Tmp.Vector3[0].y = path[j].y;
  63563. }
  63564. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  63565. BABYLON.Tmp.Vector3[1].y = path[j].y;
  63566. }
  63567. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  63568. BABYLON.Tmp.Vector3[0].z = path[j].z;
  63569. }
  63570. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  63571. BABYLON.Tmp.Vector3[1].z = path[j].z;
  63572. }
  63573. j++;
  63574. i += 3;
  63575. }
  63576. if (instance._closePath) {
  63577. positions[i] = path[0].x;
  63578. positions[i + 1] = path[0].y;
  63579. positions[i + 2] = path[0].z;
  63580. i += 3;
  63581. }
  63582. }
  63583. }
  63584. };
  63585. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63586. positionFunction(positions);
  63587. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  63588. instance._boundingInfo.update(instance._worldMatrix);
  63589. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  63590. if (options.colors) {
  63591. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63592. for (var c = 0; c < options.colors.length; c++) {
  63593. colors[c * 4] = options.colors[c].r;
  63594. colors[c * 4 + 1] = options.colors[c].g;
  63595. colors[c * 4 + 2] = options.colors[c].b;
  63596. colors[c * 4 + 3] = options.colors[c].a;
  63597. }
  63598. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  63599. }
  63600. if (options.uvs) {
  63601. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63602. for (var i = 0; i < options.uvs.length; i++) {
  63603. uvs[i * 2] = options.uvs[i].x;
  63604. uvs[i * 2 + 1] = options.uvs[i].y;
  63605. }
  63606. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  63607. }
  63608. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  63609. var indices = instance.getIndices();
  63610. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63611. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  63612. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  63613. if (instance._closePath) {
  63614. var indexFirst = 0;
  63615. var indexLast = 0;
  63616. for (var p = 0; p < pathArray.length; p++) {
  63617. indexFirst = instance._idx[p] * 3;
  63618. if (p + 1 < pathArray.length) {
  63619. indexLast = (instance._idx[p + 1] - 1) * 3;
  63620. }
  63621. else {
  63622. indexLast = normals.length - 3;
  63623. }
  63624. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  63625. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  63626. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  63627. normals[indexLast] = normals[indexFirst];
  63628. normals[indexLast + 1] = normals[indexFirst + 1];
  63629. normals[indexLast + 2] = normals[indexFirst + 2];
  63630. }
  63631. }
  63632. if (!(instance.areNormalsFrozen)) {
  63633. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  63634. }
  63635. }
  63636. return instance;
  63637. }
  63638. else { // new ribbon creation
  63639. var ribbon = new BABYLON.Mesh(name, scene);
  63640. ribbon._originalBuilderSideOrientation = sideOrientation;
  63641. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  63642. if (closePath) {
  63643. ribbon._idx = vertexData._idx;
  63644. }
  63645. ribbon._closePath = closePath;
  63646. ribbon._closeArray = closeArray;
  63647. vertexData.applyToMesh(ribbon, updatable);
  63648. return ribbon;
  63649. }
  63650. };
  63651. /**
  63652. * Creates a cylinder or a cone mesh
  63653. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  63654. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  63655. * * 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.
  63656. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  63657. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  63658. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  63659. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  63660. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  63661. * * 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).
  63662. * * 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
  63663. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  63664. * * 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
  63665. * * 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.
  63666. * * If `enclose` is false, a ring surface is one element.
  63667. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  63668. * * 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
  63669. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63670. * * 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
  63671. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63672. * @param name defines the name of the mesh
  63673. * @param options defines the options used to create the mesh
  63674. * @param scene defines the hosting scene
  63675. * @returns the cylinder mesh
  63676. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  63677. */
  63678. MeshBuilder.CreateCylinder = function (name, options, scene) {
  63679. var cylinder = new BABYLON.Mesh(name, scene);
  63680. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63681. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  63682. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  63683. vertexData.applyToMesh(cylinder, options.updatable);
  63684. return cylinder;
  63685. };
  63686. /**
  63687. * Creates a torus mesh
  63688. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  63689. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  63690. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  63691. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63692. * * 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
  63693. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63694. * @param name defines the name of the mesh
  63695. * @param options defines the options used to create the mesh
  63696. * @param scene defines the hosting scene
  63697. * @returns the torus mesh
  63698. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  63699. */
  63700. MeshBuilder.CreateTorus = function (name, options, scene) {
  63701. var torus = new BABYLON.Mesh(name, scene);
  63702. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63703. torus._originalBuilderSideOrientation = options.sideOrientation;
  63704. var vertexData = BABYLON.VertexData.CreateTorus(options);
  63705. vertexData.applyToMesh(torus, options.updatable);
  63706. return torus;
  63707. };
  63708. /**
  63709. * Creates a torus knot mesh
  63710. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  63711. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  63712. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  63713. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  63714. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63715. * * 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
  63716. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63717. * @param name defines the name of the mesh
  63718. * @param options defines the options used to create the mesh
  63719. * @param scene defines the hosting scene
  63720. * @returns the torus knot mesh
  63721. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  63722. */
  63723. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  63724. var torusKnot = new BABYLON.Mesh(name, scene);
  63725. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63726. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  63727. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  63728. vertexData.applyToMesh(torusKnot, options.updatable);
  63729. return torusKnot;
  63730. };
  63731. /**
  63732. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  63733. * * 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
  63734. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  63735. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  63736. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  63737. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  63738. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  63739. * * 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
  63740. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  63741. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63742. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  63743. * @param name defines the name of the new line system
  63744. * @param options defines the options used to create the line system
  63745. * @param scene defines the hosting scene
  63746. * @returns a new line system mesh
  63747. */
  63748. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  63749. var instance = options.instance;
  63750. var lines = options.lines;
  63751. var colors = options.colors;
  63752. if (instance) { // lines update
  63753. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63754. var vertexColor;
  63755. var lineColors;
  63756. if (colors) {
  63757. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63758. }
  63759. var i = 0;
  63760. var c = 0;
  63761. for (var l = 0; l < lines.length; l++) {
  63762. var points = lines[l];
  63763. for (var p = 0; p < points.length; p++) {
  63764. positions[i] = points[p].x;
  63765. positions[i + 1] = points[p].y;
  63766. positions[i + 2] = points[p].z;
  63767. if (colors && vertexColor) {
  63768. lineColors = colors[l];
  63769. vertexColor[c] = lineColors[p].r;
  63770. vertexColor[c + 1] = lineColors[p].g;
  63771. vertexColor[c + 2] = lineColors[p].b;
  63772. vertexColor[c + 3] = lineColors[p].a;
  63773. c += 4;
  63774. }
  63775. i += 3;
  63776. }
  63777. }
  63778. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  63779. if (colors && vertexColor) {
  63780. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  63781. }
  63782. return instance;
  63783. }
  63784. // line system creation
  63785. var useVertexColor = (colors) ? true : false;
  63786. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  63787. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  63788. vertexData.applyToMesh(lineSystem, options.updatable);
  63789. return lineSystem;
  63790. };
  63791. /**
  63792. * Creates a line mesh
  63793. * 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
  63794. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  63795. * * The parameter `points` is an array successive Vector3
  63796. * * 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
  63797. * * The optional parameter `colors` is an array of successive Color4, one per line point
  63798. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  63799. * * When updating an instance, remember that only point positions can change, not the number of points
  63800. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63801. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  63802. * @param name defines the name of the new line system
  63803. * @param options defines the options used to create the line system
  63804. * @param scene defines the hosting scene
  63805. * @returns a new line mesh
  63806. */
  63807. MeshBuilder.CreateLines = function (name, options, scene) {
  63808. if (scene === void 0) { scene = null; }
  63809. var colors = (options.colors) ? [options.colors] : null;
  63810. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  63811. return lines;
  63812. };
  63813. /**
  63814. * Creates a dashed line mesh
  63815. * * 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
  63816. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  63817. * * The parameter `points` is an array successive Vector3
  63818. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  63819. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  63820. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  63821. * * 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
  63822. * * When updating an instance, remember that only point positions can change, not the number of points
  63823. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63824. * @param name defines the name of the mesh
  63825. * @param options defines the options used to create the mesh
  63826. * @param scene defines the hosting scene
  63827. * @returns the dashed line mesh
  63828. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  63829. */
  63830. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  63831. if (scene === void 0) { scene = null; }
  63832. var points = options.points;
  63833. var instance = options.instance;
  63834. var gapSize = options.gapSize || 1;
  63835. var dashSize = options.dashSize || 3;
  63836. if (instance) { // dashed lines update
  63837. var positionFunction = function (positions) {
  63838. var curvect = BABYLON.Vector3.Zero();
  63839. var nbSeg = positions.length / 6;
  63840. var lg = 0;
  63841. var nb = 0;
  63842. var shft = 0;
  63843. var dashshft = 0;
  63844. var curshft = 0;
  63845. var p = 0;
  63846. var i = 0;
  63847. var j = 0;
  63848. for (i = 0; i < points.length - 1; i++) {
  63849. points[i + 1].subtractToRef(points[i], curvect);
  63850. lg += curvect.length();
  63851. }
  63852. shft = lg / nbSeg;
  63853. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  63854. for (i = 0; i < points.length - 1; i++) {
  63855. points[i + 1].subtractToRef(points[i], curvect);
  63856. nb = Math.floor(curvect.length() / shft);
  63857. curvect.normalize();
  63858. j = 0;
  63859. while (j < nb && p < positions.length) {
  63860. curshft = shft * j;
  63861. positions[p] = points[i].x + curshft * curvect.x;
  63862. positions[p + 1] = points[i].y + curshft * curvect.y;
  63863. positions[p + 2] = points[i].z + curshft * curvect.z;
  63864. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  63865. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  63866. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  63867. p += 6;
  63868. j++;
  63869. }
  63870. }
  63871. while (p < positions.length) {
  63872. positions[p] = points[i].x;
  63873. positions[p + 1] = points[i].y;
  63874. positions[p + 2] = points[i].z;
  63875. p += 3;
  63876. }
  63877. };
  63878. instance.updateMeshPositions(positionFunction, false);
  63879. return instance;
  63880. }
  63881. // dashed lines creation
  63882. var dashedLines = new BABYLON.LinesMesh(name, scene);
  63883. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  63884. vertexData.applyToMesh(dashedLines, options.updatable);
  63885. dashedLines.dashSize = dashSize;
  63886. dashedLines.gapSize = gapSize;
  63887. return dashedLines;
  63888. };
  63889. /**
  63890. * 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.
  63891. * * 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.
  63892. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  63893. * * 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.
  63894. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  63895. * * 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
  63896. * * 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
  63897. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  63898. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63899. * * 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
  63900. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  63901. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63902. * @param name defines the name of the mesh
  63903. * @param options defines the options used to create the mesh
  63904. * @param scene defines the hosting scene
  63905. * @returns the extruded shape mesh
  63906. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63907. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  63908. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  63909. */
  63910. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  63911. if (scene === void 0) { scene = null; }
  63912. var path = options.path;
  63913. var shape = options.shape;
  63914. var scale = options.scale || 1;
  63915. var rotation = options.rotation || 0;
  63916. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  63917. var updatable = options.updatable;
  63918. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63919. var instance = options.instance || null;
  63920. var invertUV = options.invertUV || false;
  63921. 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);
  63922. };
  63923. /**
  63924. * Creates an custom extruded shape mesh.
  63925. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  63926. * * 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.
  63927. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  63928. * * 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
  63929. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  63930. * * 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
  63931. * * It must returns a float value that will be the scale value applied to the shape on each path point
  63932. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  63933. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  63934. * * 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
  63935. * * 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
  63936. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  63937. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63938. * * 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
  63939. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63940. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63941. * @param name defines the name of the mesh
  63942. * @param options defines the options used to create the mesh
  63943. * @param scene defines the hosting scene
  63944. * @returns the custom extruded shape mesh
  63945. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  63946. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63947. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  63948. */
  63949. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  63950. var path = options.path;
  63951. var shape = options.shape;
  63952. var scaleFunction = options.scaleFunction || (function () { return 1; });
  63953. var rotationFunction = options.rotationFunction || (function () { return 0; });
  63954. var ribbonCloseArray = options.ribbonCloseArray || false;
  63955. var ribbonClosePath = options.ribbonClosePath || false;
  63956. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  63957. var updatable = options.updatable;
  63958. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63959. var instance = options.instance;
  63960. var invertUV = options.invertUV || false;
  63961. 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);
  63962. };
  63963. /**
  63964. * Creates lathe mesh.
  63965. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  63966. * * 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
  63967. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  63968. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  63969. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  63970. * * 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
  63971. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  63972. * * 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
  63973. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63974. * * 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
  63975. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63976. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63977. * @param name defines the name of the mesh
  63978. * @param options defines the options used to create the mesh
  63979. * @param scene defines the hosting scene
  63980. * @returns the lathe mesh
  63981. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  63982. */
  63983. MeshBuilder.CreateLathe = function (name, options, scene) {
  63984. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  63985. var closed = (options.closed === undefined) ? true : options.closed;
  63986. var shape = options.shape;
  63987. var radius = options.radius || 1;
  63988. var tessellation = options.tessellation || 64;
  63989. var clip = options.clip || 0;
  63990. var updatable = options.updatable;
  63991. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63992. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  63993. var pi2 = Math.PI * 2;
  63994. var paths = new Array();
  63995. var invertUV = options.invertUV || false;
  63996. var i = 0;
  63997. var p = 0;
  63998. var step = pi2 / tessellation * arc;
  63999. var rotated;
  64000. var path = new Array();
  64001. for (i = 0; i <= tessellation - clip; i++) {
  64002. var path = [];
  64003. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  64004. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  64005. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  64006. }
  64007. for (p = 0; p < shape.length; p++) {
  64008. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  64009. path.push(rotated);
  64010. }
  64011. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  64012. 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));
  64013. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  64014. }
  64015. paths.push(path);
  64016. }
  64017. // lathe ribbon
  64018. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  64019. return lathe;
  64020. };
  64021. /**
  64022. * Creates a plane mesh
  64023. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  64024. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  64025. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  64026. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64027. * * 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
  64028. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64029. * @param name defines the name of the mesh
  64030. * @param options defines the options used to create the mesh
  64031. * @param scene defines the hosting scene
  64032. * @returns the plane mesh
  64033. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  64034. */
  64035. MeshBuilder.CreatePlane = function (name, options, scene) {
  64036. var plane = new BABYLON.Mesh(name, scene);
  64037. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64038. plane._originalBuilderSideOrientation = options.sideOrientation;
  64039. var vertexData = BABYLON.VertexData.CreatePlane(options);
  64040. vertexData.applyToMesh(plane, options.updatable);
  64041. if (options.sourcePlane) {
  64042. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  64043. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  64044. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  64045. plane.rotate(vectorProduct, product);
  64046. }
  64047. return plane;
  64048. };
  64049. /**
  64050. * Creates a ground mesh
  64051. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  64052. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  64053. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64054. * @param name defines the name of the mesh
  64055. * @param options defines the options used to create the mesh
  64056. * @param scene defines the hosting scene
  64057. * @returns the ground mesh
  64058. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  64059. */
  64060. MeshBuilder.CreateGround = function (name, options, scene) {
  64061. var ground = new BABYLON.GroundMesh(name, scene);
  64062. ground._setReady(false);
  64063. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  64064. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  64065. ground._width = options.width || 1;
  64066. ground._height = options.height || 1;
  64067. ground._maxX = ground._width / 2;
  64068. ground._maxZ = ground._height / 2;
  64069. ground._minX = -ground._maxX;
  64070. ground._minZ = -ground._maxZ;
  64071. var vertexData = BABYLON.VertexData.CreateGround(options);
  64072. vertexData.applyToMesh(ground, options.updatable);
  64073. ground._setReady(true);
  64074. return ground;
  64075. };
  64076. /**
  64077. * Creates a tiled ground mesh
  64078. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  64079. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  64080. * * 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
  64081. * * 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
  64082. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64083. * @param name defines the name of the mesh
  64084. * @param options defines the options used to create the mesh
  64085. * @param scene defines the hosting scene
  64086. * @returns the tiled ground mesh
  64087. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  64088. */
  64089. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  64090. var tiledGround = new BABYLON.Mesh(name, scene);
  64091. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  64092. vertexData.applyToMesh(tiledGround, options.updatable);
  64093. return tiledGround;
  64094. };
  64095. /**
  64096. * Creates a ground mesh from a height map
  64097. * * The parameter `url` sets the URL of the height map image resource.
  64098. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  64099. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  64100. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  64101. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  64102. * * 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.
  64103. * * 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).
  64104. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64105. * @param name defines the name of the mesh
  64106. * @param url defines the url to the height map
  64107. * @param options defines the options used to create the mesh
  64108. * @param scene defines the hosting scene
  64109. * @returns the ground mesh
  64110. * @see http://doc.babylonjs.com/babylon101/height_map
  64111. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  64112. */
  64113. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  64114. var width = options.width || 10.0;
  64115. var height = options.height || 10.0;
  64116. var subdivisions = options.subdivisions || 1 | 0;
  64117. var minHeight = options.minHeight || 0.0;
  64118. var maxHeight = options.maxHeight || 1.0;
  64119. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  64120. var updatable = options.updatable;
  64121. var onReady = options.onReady;
  64122. var ground = new BABYLON.GroundMesh(name, scene);
  64123. ground._subdivisionsX = subdivisions;
  64124. ground._subdivisionsY = subdivisions;
  64125. ground._width = width;
  64126. ground._height = height;
  64127. ground._maxX = ground._width / 2.0;
  64128. ground._maxZ = ground._height / 2.0;
  64129. ground._minX = -ground._maxX;
  64130. ground._minZ = -ground._maxZ;
  64131. ground._setReady(false);
  64132. var onload = function (img) {
  64133. // Getting height map data
  64134. var canvas = document.createElement("canvas");
  64135. var context = canvas.getContext("2d");
  64136. if (!context) {
  64137. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  64138. }
  64139. if (scene.isDisposed) {
  64140. return;
  64141. }
  64142. var bufferWidth = img.width;
  64143. var bufferHeight = img.height;
  64144. canvas.width = bufferWidth;
  64145. canvas.height = bufferHeight;
  64146. context.drawImage(img, 0, 0);
  64147. // Create VertexData from map data
  64148. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  64149. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  64150. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  64151. width: width, height: height,
  64152. subdivisions: subdivisions,
  64153. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  64154. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  64155. });
  64156. vertexData.applyToMesh(ground, updatable);
  64157. //execute ready callback, if set
  64158. if (onReady) {
  64159. onReady(ground);
  64160. }
  64161. ground._setReady(true);
  64162. };
  64163. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  64164. return ground;
  64165. };
  64166. /**
  64167. * Creates a polygon mesh
  64168. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  64169. * * 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
  64170. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64171. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64172. * * 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)
  64173. * * Remember you can only change the shape positions, not their number when updating a polygon
  64174. * @param name defines the name of the mesh
  64175. * @param options defines the options used to create the mesh
  64176. * @param scene defines the hosting scene
  64177. * @returns the polygon mesh
  64178. */
  64179. MeshBuilder.CreatePolygon = function (name, options, scene) {
  64180. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64181. var shape = options.shape;
  64182. var holes = options.holes || [];
  64183. var depth = options.depth || 0;
  64184. var contours = [];
  64185. var hole = [];
  64186. for (var i = 0; i < shape.length; i++) {
  64187. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  64188. }
  64189. var epsilon = 0.00000001;
  64190. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  64191. contours.pop();
  64192. }
  64193. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  64194. for (var hNb = 0; hNb < holes.length; hNb++) {
  64195. hole = [];
  64196. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  64197. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  64198. }
  64199. polygonTriangulation.addHole(hole);
  64200. }
  64201. var polygon = polygonTriangulation.build(options.updatable, depth);
  64202. polygon._originalBuilderSideOrientation = options.sideOrientation;
  64203. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  64204. vertexData.applyToMesh(polygon, options.updatable);
  64205. return polygon;
  64206. };
  64207. ;
  64208. /**
  64209. * Creates an extruded polygon mesh, with depth in the Y direction.
  64210. * * 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)
  64211. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  64212. * @param name defines the name of the mesh
  64213. * @param options defines the options used to create the mesh
  64214. * @param scene defines the hosting scene
  64215. * @returns the polygon mesh
  64216. */
  64217. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  64218. return MeshBuilder.CreatePolygon(name, options, scene);
  64219. };
  64220. ;
  64221. /**
  64222. * Creates a tube mesh.
  64223. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  64224. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  64225. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  64226. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  64227. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  64228. * * 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)
  64229. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  64230. * * 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
  64231. * * 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
  64232. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64233. * * 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
  64234. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64235. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64236. * @param name defines the name of the mesh
  64237. * @param options defines the options used to create the mesh
  64238. * @param scene defines the hosting scene
  64239. * @returns the tube mesh
  64240. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64241. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  64242. */
  64243. MeshBuilder.CreateTube = function (name, options, scene) {
  64244. var path = options.path;
  64245. var instance = options.instance;
  64246. var radius = 1.0;
  64247. if (instance) {
  64248. radius = instance.radius;
  64249. }
  64250. if (options.radius !== undefined) {
  64251. radius = options.radius;
  64252. }
  64253. ;
  64254. var tessellation = options.tessellation || 64 | 0;
  64255. var radiusFunction = options.radiusFunction || null;
  64256. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  64257. var invertUV = options.invertUV || false;
  64258. var updatable = options.updatable;
  64259. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64260. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  64261. // tube geometry
  64262. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  64263. var tangents = path3D.getTangents();
  64264. var normals = path3D.getNormals();
  64265. var distances = path3D.getDistances();
  64266. var pi2 = Math.PI * 2;
  64267. var step = pi2 / tessellation * arc;
  64268. var returnRadius = function () { return radius; };
  64269. var radiusFunctionFinal = radiusFunction || returnRadius;
  64270. var circlePath;
  64271. var rad;
  64272. var normal;
  64273. var rotated;
  64274. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  64275. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  64276. for (var i = 0; i < path.length; i++) {
  64277. rad = radiusFunctionFinal(i, distances[i]); // current radius
  64278. circlePath = Array(); // current circle array
  64279. normal = normals[i]; // current normal
  64280. for (var t = 0; t < tessellation; t++) {
  64281. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  64282. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  64283. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  64284. rotated.scaleInPlace(rad).addInPlace(path[i]);
  64285. circlePath[t] = rotated;
  64286. }
  64287. circlePaths[index] = circlePath;
  64288. index++;
  64289. }
  64290. // cap
  64291. var capPath = function (nbPoints, pathIndex) {
  64292. var pointCap = Array();
  64293. for (var i = 0; i < nbPoints; i++) {
  64294. pointCap.push(path[pathIndex]);
  64295. }
  64296. return pointCap;
  64297. };
  64298. switch (cap) {
  64299. case BABYLON.Mesh.NO_CAP:
  64300. break;
  64301. case BABYLON.Mesh.CAP_START:
  64302. circlePaths[0] = capPath(tessellation, 0);
  64303. circlePaths[1] = circlePaths[2].slice(0);
  64304. break;
  64305. case BABYLON.Mesh.CAP_END:
  64306. circlePaths[index] = circlePaths[index - 1].slice(0);
  64307. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  64308. break;
  64309. case BABYLON.Mesh.CAP_ALL:
  64310. circlePaths[0] = capPath(tessellation, 0);
  64311. circlePaths[1] = circlePaths[2].slice(0);
  64312. circlePaths[index] = circlePaths[index - 1].slice(0);
  64313. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  64314. break;
  64315. default:
  64316. break;
  64317. }
  64318. return circlePaths;
  64319. };
  64320. var path3D;
  64321. var pathArray;
  64322. if (instance) { // tube update
  64323. var arc = options.arc || instance.arc;
  64324. path3D = (instance.path3D).update(path);
  64325. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  64326. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  64327. instance.path3D = path3D;
  64328. instance.pathArray = pathArray;
  64329. instance.arc = arc;
  64330. instance.radius = radius;
  64331. return instance;
  64332. }
  64333. // tube creation
  64334. path3D = new BABYLON.Path3D(path);
  64335. var newPathArray = new Array();
  64336. cap = (cap < 0 || cap > 3) ? 0 : cap;
  64337. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  64338. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  64339. tube.pathArray = pathArray;
  64340. tube.path3D = path3D;
  64341. tube.tessellation = tessellation;
  64342. tube.cap = cap;
  64343. tube.arc = options.arc;
  64344. tube.radius = radius;
  64345. return tube;
  64346. };
  64347. /**
  64348. * Creates a polyhedron mesh
  64349. * * 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
  64350. * * The parameter `size` (positive float, default 1) sets the polygon size
  64351. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  64352. * * 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`
  64353. * * 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
  64354. * * 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)`)
  64355. * * 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
  64356. * * 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
  64357. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64358. * * 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
  64359. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64360. * @param name defines the name of the mesh
  64361. * @param options defines the options used to create the mesh
  64362. * @param scene defines the hosting scene
  64363. * @returns the polyhedron mesh
  64364. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  64365. */
  64366. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  64367. var polyhedron = new BABYLON.Mesh(name, scene);
  64368. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64369. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  64370. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  64371. vertexData.applyToMesh(polyhedron, options.updatable);
  64372. return polyhedron;
  64373. };
  64374. /**
  64375. * Creates a decal mesh.
  64376. * 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
  64377. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  64378. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  64379. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  64380. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  64381. * @param name defines the name of the mesh
  64382. * @param sourceMesh defines the mesh where the decal must be applied
  64383. * @param options defines the options used to create the mesh
  64384. * @param scene defines the hosting scene
  64385. * @returns the decal mesh
  64386. * @see http://doc.babylonjs.com/how_to/decals
  64387. */
  64388. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  64389. var indices = sourceMesh.getIndices();
  64390. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64391. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64392. var position = options.position || BABYLON.Vector3.Zero();
  64393. var normal = options.normal || BABYLON.Vector3.Up();
  64394. var size = options.size || BABYLON.Vector3.One();
  64395. var angle = options.angle || 0;
  64396. // Getting correct rotation
  64397. if (!normal) {
  64398. var target = new BABYLON.Vector3(0, 0, 1);
  64399. var camera = sourceMesh.getScene().activeCamera;
  64400. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  64401. normal = camera.globalPosition.subtract(cameraWorldTarget);
  64402. }
  64403. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  64404. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  64405. var pitch = Math.atan2(normal.y, len);
  64406. // Matrix
  64407. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  64408. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  64409. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  64410. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  64411. var vertexData = new BABYLON.VertexData();
  64412. vertexData.indices = [];
  64413. vertexData.positions = [];
  64414. vertexData.normals = [];
  64415. vertexData.uvs = [];
  64416. var currentVertexDataIndex = 0;
  64417. var extractDecalVector3 = function (indexId) {
  64418. var result = new BABYLON.PositionNormalVertex();
  64419. if (!indices || !positions || !normals) {
  64420. return result;
  64421. }
  64422. var vertexId = indices[indexId];
  64423. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  64424. // Send vector to decal local world
  64425. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  64426. // Get normal
  64427. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  64428. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  64429. return result;
  64430. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  64431. var clip = function (vertices, axis) {
  64432. if (vertices.length === 0) {
  64433. return vertices;
  64434. }
  64435. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  64436. var clipVertices = function (v0, v1) {
  64437. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  64438. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  64439. };
  64440. var result = new Array();
  64441. for (var index = 0; index < vertices.length; index += 3) {
  64442. var v1Out;
  64443. var v2Out;
  64444. var v3Out;
  64445. var total = 0;
  64446. var nV1 = null;
  64447. var nV2 = null;
  64448. var nV3 = null;
  64449. var nV4 = null;
  64450. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  64451. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  64452. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  64453. v1Out = d1 > 0;
  64454. v2Out = d2 > 0;
  64455. v3Out = d3 > 0;
  64456. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  64457. switch (total) {
  64458. case 0:
  64459. result.push(vertices[index]);
  64460. result.push(vertices[index + 1]);
  64461. result.push(vertices[index + 2]);
  64462. break;
  64463. case 1:
  64464. if (v1Out) {
  64465. nV1 = vertices[index + 1];
  64466. nV2 = vertices[index + 2];
  64467. nV3 = clipVertices(vertices[index], nV1);
  64468. nV4 = clipVertices(vertices[index], nV2);
  64469. }
  64470. if (v2Out) {
  64471. nV1 = vertices[index];
  64472. nV2 = vertices[index + 2];
  64473. nV3 = clipVertices(vertices[index + 1], nV1);
  64474. nV4 = clipVertices(vertices[index + 1], nV2);
  64475. result.push(nV3);
  64476. result.push(nV2.clone());
  64477. result.push(nV1.clone());
  64478. result.push(nV2.clone());
  64479. result.push(nV3.clone());
  64480. result.push(nV4);
  64481. break;
  64482. }
  64483. if (v3Out) {
  64484. nV1 = vertices[index];
  64485. nV2 = vertices[index + 1];
  64486. nV3 = clipVertices(vertices[index + 2], nV1);
  64487. nV4 = clipVertices(vertices[index + 2], nV2);
  64488. }
  64489. if (nV1 && nV2 && nV3 && nV4) {
  64490. result.push(nV1.clone());
  64491. result.push(nV2.clone());
  64492. result.push(nV3);
  64493. result.push(nV4);
  64494. result.push(nV3.clone());
  64495. result.push(nV2.clone());
  64496. }
  64497. break;
  64498. case 2:
  64499. if (!v1Out) {
  64500. nV1 = vertices[index].clone();
  64501. nV2 = clipVertices(nV1, vertices[index + 1]);
  64502. nV3 = clipVertices(nV1, vertices[index + 2]);
  64503. result.push(nV1);
  64504. result.push(nV2);
  64505. result.push(nV3);
  64506. }
  64507. if (!v2Out) {
  64508. nV1 = vertices[index + 1].clone();
  64509. nV2 = clipVertices(nV1, vertices[index + 2]);
  64510. nV3 = clipVertices(nV1, vertices[index]);
  64511. result.push(nV1);
  64512. result.push(nV2);
  64513. result.push(nV3);
  64514. }
  64515. if (!v3Out) {
  64516. nV1 = vertices[index + 2].clone();
  64517. nV2 = clipVertices(nV1, vertices[index]);
  64518. nV3 = clipVertices(nV1, vertices[index + 1]);
  64519. result.push(nV1);
  64520. result.push(nV2);
  64521. result.push(nV3);
  64522. }
  64523. break;
  64524. case 3:
  64525. break;
  64526. }
  64527. }
  64528. return result;
  64529. };
  64530. for (var index = 0; index < indices.length; index += 3) {
  64531. var faceVertices = new Array();
  64532. faceVertices.push(extractDecalVector3(index));
  64533. faceVertices.push(extractDecalVector3(index + 1));
  64534. faceVertices.push(extractDecalVector3(index + 2));
  64535. // Clip
  64536. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  64537. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  64538. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  64539. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  64540. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  64541. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  64542. if (faceVertices.length === 0) {
  64543. continue;
  64544. }
  64545. // Add UVs and get back to world
  64546. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  64547. var vertex = faceVertices[vIndex];
  64548. //TODO check for Int32Array | Uint32Array | Uint16Array
  64549. vertexData.indices.push(currentVertexDataIndex);
  64550. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  64551. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  64552. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  64553. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  64554. currentVertexDataIndex++;
  64555. }
  64556. }
  64557. // Return mesh
  64558. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  64559. vertexData.applyToMesh(decal);
  64560. decal.position = position.clone();
  64561. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  64562. return decal;
  64563. };
  64564. // Privates
  64565. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  64566. // extrusion geometry
  64567. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  64568. var tangents = path3D.getTangents();
  64569. var normals = path3D.getNormals();
  64570. var binormals = path3D.getBinormals();
  64571. var distances = path3D.getDistances();
  64572. var angle = 0;
  64573. var returnScale = function () { return scale !== null ? scale : 1; };
  64574. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  64575. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  64576. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  64577. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  64578. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  64579. for (var i = 0; i < curve.length; i++) {
  64580. var shapePath = new Array();
  64581. var angleStep = rotate(i, distances[i]);
  64582. var scaleRatio = scl(i, distances[i]);
  64583. for (var p = 0; p < shape.length; p++) {
  64584. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  64585. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  64586. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  64587. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  64588. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  64589. shapePath[p] = rotated;
  64590. }
  64591. shapePaths[index] = shapePath;
  64592. angle += angleStep;
  64593. index++;
  64594. }
  64595. // cap
  64596. var capPath = function (shapePath) {
  64597. var pointCap = Array();
  64598. var barycenter = BABYLON.Vector3.Zero();
  64599. var i;
  64600. for (i = 0; i < shapePath.length; i++) {
  64601. barycenter.addInPlace(shapePath[i]);
  64602. }
  64603. barycenter.scaleInPlace(1.0 / shapePath.length);
  64604. for (i = 0; i < shapePath.length; i++) {
  64605. pointCap.push(barycenter);
  64606. }
  64607. return pointCap;
  64608. };
  64609. switch (cap) {
  64610. case BABYLON.Mesh.NO_CAP:
  64611. break;
  64612. case BABYLON.Mesh.CAP_START:
  64613. shapePaths[0] = capPath(shapePaths[2]);
  64614. shapePaths[1] = shapePaths[2];
  64615. break;
  64616. case BABYLON.Mesh.CAP_END:
  64617. shapePaths[index] = shapePaths[index - 1];
  64618. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  64619. break;
  64620. case BABYLON.Mesh.CAP_ALL:
  64621. shapePaths[0] = capPath(shapePaths[2]);
  64622. shapePaths[1] = shapePaths[2];
  64623. shapePaths[index] = shapePaths[index - 1];
  64624. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  64625. break;
  64626. default:
  64627. break;
  64628. }
  64629. return shapePaths;
  64630. };
  64631. var path3D;
  64632. var pathArray;
  64633. if (instance) { // instance update
  64634. path3D = (instance.path3D).update(curve);
  64635. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  64636. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  64637. return instance;
  64638. }
  64639. // extruded shape creation
  64640. path3D = new BABYLON.Path3D(curve);
  64641. var newShapePaths = new Array();
  64642. cap = (cap < 0 || cap > 3) ? 0 : cap;
  64643. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  64644. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  64645. extrudedGeneric.pathArray = pathArray;
  64646. extrudedGeneric.path3D = path3D;
  64647. extrudedGeneric.cap = cap;
  64648. return extrudedGeneric;
  64649. };
  64650. return MeshBuilder;
  64651. }());
  64652. BABYLON.MeshBuilder = MeshBuilder;
  64653. })(BABYLON || (BABYLON = {}));
  64654. //# sourceMappingURL=babylon.meshBuilder.js.map
  64655. var BABYLON;
  64656. (function (BABYLON) {
  64657. /**
  64658. * Draco compression (https://google.github.io/draco/)
  64659. *
  64660. * This class wraps the Draco module.
  64661. *
  64662. * **Encoder**
  64663. *
  64664. * The encoder is not currently implemented.
  64665. *
  64666. * **Decoder**
  64667. *
  64668. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  64669. *
  64670. * To update the configuration, use the following code:
  64671. * ```javascript
  64672. * BABYLON.DracoCompression.Configuration = {
  64673. * decoder: {
  64674. * wasmUrl: "<url to the WebAssembly library>",
  64675. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  64676. * fallbackUrl: "<url to the fallback JavaScript library>",
  64677. * }
  64678. * };
  64679. * ```
  64680. *
  64681. * 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.
  64682. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  64683. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  64684. *
  64685. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  64686. * ```javascript
  64687. * var dracoCompression = new BABYLON.DracoCompression();
  64688. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  64689. * [BABYLON.VertexBuffer.PositionKind]: 0
  64690. * });
  64691. * ```
  64692. *
  64693. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  64694. */
  64695. var DracoCompression = /** @class */ (function () {
  64696. /**
  64697. * Constructor
  64698. */
  64699. function DracoCompression() {
  64700. }
  64701. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  64702. /**
  64703. * Returns true if the decoder is available.
  64704. */
  64705. get: function () {
  64706. if (typeof DracoDecoderModule !== "undefined") {
  64707. return true;
  64708. }
  64709. var decoder = DracoCompression.Configuration.decoder;
  64710. if (decoder) {
  64711. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  64712. return true;
  64713. }
  64714. if (decoder.fallbackUrl) {
  64715. return true;
  64716. }
  64717. }
  64718. return false;
  64719. },
  64720. enumerable: true,
  64721. configurable: true
  64722. });
  64723. /**
  64724. * Stop all async operations and release resources.
  64725. */
  64726. DracoCompression.prototype.dispose = function () {
  64727. };
  64728. /**
  64729. * Decode Draco compressed mesh data to vertex data.
  64730. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  64731. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  64732. * @returns A promise that resolves with the decoded vertex data
  64733. */
  64734. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  64735. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  64736. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  64737. var module = wrappedModule.module;
  64738. var vertexData = new BABYLON.VertexData();
  64739. var buffer = new module.DecoderBuffer();
  64740. buffer.Init(dataView, dataView.byteLength);
  64741. var decoder = new module.Decoder();
  64742. var geometry;
  64743. var status;
  64744. try {
  64745. var type = decoder.GetEncodedGeometryType(buffer);
  64746. switch (type) {
  64747. case module.TRIANGULAR_MESH:
  64748. geometry = new module.Mesh();
  64749. status = decoder.DecodeBufferToMesh(buffer, geometry);
  64750. break;
  64751. case module.POINT_CLOUD:
  64752. geometry = new module.PointCloud();
  64753. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  64754. break;
  64755. default:
  64756. throw new Error("Invalid geometry type " + type);
  64757. }
  64758. if (!status.ok() || !geometry.ptr) {
  64759. throw new Error(status.error_msg());
  64760. }
  64761. var numPoints = geometry.num_points();
  64762. if (type === module.TRIANGULAR_MESH) {
  64763. var numFaces = geometry.num_faces();
  64764. var faceIndices = new module.DracoInt32Array();
  64765. try {
  64766. var indices = new Uint32Array(numFaces * 3);
  64767. for (var i = 0; i < numFaces; i++) {
  64768. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  64769. var offset = i * 3;
  64770. indices[offset + 0] = faceIndices.GetValue(0);
  64771. indices[offset + 1] = faceIndices.GetValue(1);
  64772. indices[offset + 2] = faceIndices.GetValue(2);
  64773. }
  64774. vertexData.indices = indices;
  64775. }
  64776. finally {
  64777. module.destroy(faceIndices);
  64778. }
  64779. }
  64780. for (var kind in attributes) {
  64781. var uniqueId = attributes[kind];
  64782. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  64783. var dracoData = new module.DracoFloat32Array();
  64784. try {
  64785. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  64786. var babylonData = new Float32Array(numPoints * attribute.num_components());
  64787. for (var i = 0; i < babylonData.length; i++) {
  64788. babylonData[i] = dracoData.GetValue(i);
  64789. }
  64790. vertexData.set(babylonData, kind);
  64791. }
  64792. finally {
  64793. module.destroy(dracoData);
  64794. }
  64795. }
  64796. }
  64797. finally {
  64798. if (geometry) {
  64799. module.destroy(geometry);
  64800. }
  64801. module.destroy(decoder);
  64802. module.destroy(buffer);
  64803. }
  64804. return vertexData;
  64805. });
  64806. };
  64807. DracoCompression._GetDecoderModule = function () {
  64808. if (!DracoCompression._DecoderModulePromise) {
  64809. var promise = null;
  64810. var config_1 = {};
  64811. if (typeof DracoDecoderModule !== "undefined") {
  64812. promise = Promise.resolve();
  64813. }
  64814. else {
  64815. var decoder = DracoCompression.Configuration.decoder;
  64816. if (decoder) {
  64817. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  64818. promise = Promise.all([
  64819. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  64820. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  64821. config_1.wasmBinary = data;
  64822. })
  64823. ]);
  64824. }
  64825. else if (decoder.fallbackUrl) {
  64826. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  64827. }
  64828. }
  64829. }
  64830. if (!promise) {
  64831. throw new Error("Draco decoder module is not available");
  64832. }
  64833. DracoCompression._DecoderModulePromise = promise.then(function () {
  64834. return new Promise(function (resolve) {
  64835. config_1.onModuleLoaded = function (decoderModule) {
  64836. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  64837. resolve({ module: decoderModule });
  64838. };
  64839. DracoDecoderModule(config_1);
  64840. });
  64841. });
  64842. }
  64843. return DracoCompression._DecoderModulePromise;
  64844. };
  64845. DracoCompression._LoadScriptAsync = function (url) {
  64846. return new Promise(function (resolve, reject) {
  64847. BABYLON.Tools.LoadScript(url, function () {
  64848. resolve();
  64849. }, function (message) {
  64850. reject(new Error(message));
  64851. });
  64852. });
  64853. };
  64854. DracoCompression._LoadFileAsync = function (url) {
  64855. return new Promise(function (resolve, reject) {
  64856. BABYLON.Tools.LoadFile(url, function (data) {
  64857. resolve(data);
  64858. }, undefined, undefined, true, function (request, exception) {
  64859. reject(exception);
  64860. });
  64861. });
  64862. };
  64863. /**
  64864. * The configuration. Defaults to the following urls:
  64865. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  64866. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  64867. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  64868. */
  64869. DracoCompression.Configuration = {
  64870. decoder: {
  64871. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  64872. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  64873. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  64874. }
  64875. };
  64876. return DracoCompression;
  64877. }());
  64878. BABYLON.DracoCompression = DracoCompression;
  64879. })(BABYLON || (BABYLON = {}));
  64880. //# sourceMappingURL=babylon.dracoCompression.js.map
  64881. var BABYLON;
  64882. (function (BABYLON) {
  64883. var AudioEngine = /** @class */ (function () {
  64884. function AudioEngine() {
  64885. this._audioContext = null;
  64886. this._audioContextInitialized = false;
  64887. this.canUseWebAudio = false;
  64888. this.WarnedWebAudioUnsupported = false;
  64889. this.unlocked = false;
  64890. this.isMP3supported = false;
  64891. this.isOGGsupported = false;
  64892. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  64893. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  64894. this.canUseWebAudio = true;
  64895. }
  64896. var audioElem = document.createElement('audio');
  64897. try {
  64898. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  64899. this.isMP3supported = true;
  64900. }
  64901. }
  64902. catch (e) {
  64903. // protect error during capability check.
  64904. }
  64905. try {
  64906. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  64907. this.isOGGsupported = true;
  64908. }
  64909. }
  64910. catch (e) {
  64911. // protect error during capability check.
  64912. }
  64913. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  64914. this._unlockiOSaudio();
  64915. }
  64916. else {
  64917. this.unlocked = true;
  64918. }
  64919. }
  64920. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  64921. get: function () {
  64922. if (!this._audioContextInitialized) {
  64923. this._initializeAudioContext();
  64924. }
  64925. return this._audioContext;
  64926. },
  64927. enumerable: true,
  64928. configurable: true
  64929. });
  64930. AudioEngine.prototype._unlockiOSaudio = function () {
  64931. var _this = this;
  64932. var unlockaudio = function () {
  64933. if (!_this.audioContext) {
  64934. return;
  64935. }
  64936. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  64937. var source = _this.audioContext.createBufferSource();
  64938. source.buffer = buffer;
  64939. source.connect(_this.audioContext.destination);
  64940. source.start(0);
  64941. setTimeout(function () {
  64942. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  64943. _this.unlocked = true;
  64944. window.removeEventListener('touchend', unlockaudio, false);
  64945. if (_this.onAudioUnlocked) {
  64946. _this.onAudioUnlocked();
  64947. }
  64948. }
  64949. }, 0);
  64950. };
  64951. window.addEventListener('touchend', unlockaudio, false);
  64952. };
  64953. AudioEngine.prototype._initializeAudioContext = function () {
  64954. try {
  64955. if (this.canUseWebAudio) {
  64956. this._audioContext = new AudioContext();
  64957. // create a global volume gain node
  64958. this.masterGain = this._audioContext.createGain();
  64959. this.masterGain.gain.value = 1;
  64960. this.masterGain.connect(this._audioContext.destination);
  64961. this._audioContextInitialized = true;
  64962. }
  64963. }
  64964. catch (e) {
  64965. this.canUseWebAudio = false;
  64966. BABYLON.Tools.Error("Web Audio: " + e.message);
  64967. }
  64968. };
  64969. AudioEngine.prototype.dispose = function () {
  64970. if (this.canUseWebAudio && this._audioContextInitialized) {
  64971. if (this._connectedAnalyser && this._audioContext) {
  64972. this._connectedAnalyser.stopDebugCanvas();
  64973. this._connectedAnalyser.dispose();
  64974. this.masterGain.disconnect();
  64975. this.masterGain.connect(this._audioContext.destination);
  64976. this._connectedAnalyser = null;
  64977. }
  64978. this.masterGain.gain.value = 1;
  64979. }
  64980. this.WarnedWebAudioUnsupported = false;
  64981. };
  64982. AudioEngine.prototype.getGlobalVolume = function () {
  64983. if (this.canUseWebAudio && this._audioContextInitialized) {
  64984. return this.masterGain.gain.value;
  64985. }
  64986. else {
  64987. return -1;
  64988. }
  64989. };
  64990. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  64991. if (this.canUseWebAudio && this._audioContextInitialized) {
  64992. this.masterGain.gain.value = newVolume;
  64993. }
  64994. };
  64995. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  64996. if (this._connectedAnalyser) {
  64997. this._connectedAnalyser.stopDebugCanvas();
  64998. }
  64999. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  65000. this._connectedAnalyser = analyser;
  65001. this.masterGain.disconnect();
  65002. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  65003. }
  65004. };
  65005. return AudioEngine;
  65006. }());
  65007. BABYLON.AudioEngine = AudioEngine;
  65008. })(BABYLON || (BABYLON = {}));
  65009. //# sourceMappingURL=babylon.audioEngine.js.map
  65010. var BABYLON;
  65011. (function (BABYLON) {
  65012. var Sound = /** @class */ (function () {
  65013. /**
  65014. * Create a sound and attach it to a scene
  65015. * @param name Name of your sound
  65016. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  65017. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  65018. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  65019. */
  65020. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  65021. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  65022. var _this = this;
  65023. this.autoplay = false;
  65024. this.loop = false;
  65025. this.useCustomAttenuation = false;
  65026. this.spatialSound = false;
  65027. this.refDistance = 1;
  65028. this.rolloffFactor = 1;
  65029. this.maxDistance = 100;
  65030. this.distanceModel = "linear";
  65031. this._panningModel = "equalpower";
  65032. /**
  65033. * Observable event when the current playing sound finishes.
  65034. */
  65035. this.onEndedObservable = new BABYLON.Observable();
  65036. this._playbackRate = 1;
  65037. this._streaming = false;
  65038. this._startTime = 0;
  65039. this._startOffset = 0;
  65040. this._position = BABYLON.Vector3.Zero();
  65041. /** @hidden */
  65042. this._positionInEmitterSpace = false;
  65043. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  65044. this._volume = 1;
  65045. this._isReadyToPlay = false;
  65046. this.isPlaying = false;
  65047. this.isPaused = false;
  65048. this._isDirectional = false;
  65049. // Used if you'd like to create a directional sound.
  65050. // If not set, the sound will be omnidirectional
  65051. this._coneInnerAngle = 360;
  65052. this._coneOuterAngle = 360;
  65053. this._coneOuterGain = 0;
  65054. this._isOutputConnected = false;
  65055. this._urlType = "Unknown";
  65056. this.name = name;
  65057. this._scene = scene;
  65058. this._readyToPlayCallback = readyToPlayCallback;
  65059. // Default custom attenuation function is a linear attenuation
  65060. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  65061. if (currentDistance < maxDistance) {
  65062. return currentVolume * (1 - currentDistance / maxDistance);
  65063. }
  65064. else {
  65065. return 0;
  65066. }
  65067. };
  65068. if (options) {
  65069. this.autoplay = options.autoplay || false;
  65070. this.loop = options.loop || false;
  65071. // if volume === 0, we need another way to check this option
  65072. if (options.volume !== undefined) {
  65073. this._volume = options.volume;
  65074. }
  65075. this.spatialSound = options.spatialSound || false;
  65076. this.maxDistance = options.maxDistance || 100;
  65077. this.useCustomAttenuation = options.useCustomAttenuation || false;
  65078. this.rolloffFactor = options.rolloffFactor || 1;
  65079. this.refDistance = options.refDistance || 1;
  65080. this.distanceModel = options.distanceModel || "linear";
  65081. this._playbackRate = options.playbackRate || 1;
  65082. this._streaming = options.streaming || false;
  65083. }
  65084. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65085. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  65086. this._soundGain.gain.value = this._volume;
  65087. this._inputAudioNode = this._soundGain;
  65088. this._outputAudioNode = this._soundGain;
  65089. if (this.spatialSound) {
  65090. this._createSpatialParameters();
  65091. }
  65092. this._scene.mainSoundTrack.AddSound(this);
  65093. var validParameter = true;
  65094. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  65095. if (urlOrArrayBuffer) {
  65096. try {
  65097. if (typeof (urlOrArrayBuffer) === "string") {
  65098. this._urlType = "String";
  65099. }
  65100. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  65101. this._urlType = "ArrayBuffer";
  65102. }
  65103. else if (urlOrArrayBuffer instanceof MediaStream) {
  65104. this._urlType = "MediaStream";
  65105. }
  65106. else if (Array.isArray(urlOrArrayBuffer)) {
  65107. this._urlType = "Array";
  65108. }
  65109. var urls = [];
  65110. var codecSupportedFound = false;
  65111. switch (this._urlType) {
  65112. case "MediaStream":
  65113. this._streaming = true;
  65114. this._isReadyToPlay = true;
  65115. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  65116. if (this.autoplay) {
  65117. this.play();
  65118. }
  65119. if (this._readyToPlayCallback) {
  65120. this._readyToPlayCallback();
  65121. }
  65122. break;
  65123. case "ArrayBuffer":
  65124. if (urlOrArrayBuffer.byteLength > 0) {
  65125. codecSupportedFound = true;
  65126. this._soundLoaded(urlOrArrayBuffer);
  65127. }
  65128. break;
  65129. case "String":
  65130. urls.push(urlOrArrayBuffer);
  65131. case "Array":
  65132. if (urls.length === 0)
  65133. urls = urlOrArrayBuffer;
  65134. // If we found a supported format, we load it immediately and stop the loop
  65135. for (var i = 0; i < urls.length; i++) {
  65136. var url = urls[i];
  65137. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  65138. codecSupportedFound = true;
  65139. }
  65140. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  65141. codecSupportedFound = true;
  65142. }
  65143. if (url.indexOf(".wav", url.length - 4) !== -1) {
  65144. codecSupportedFound = true;
  65145. }
  65146. if (url.indexOf("blob:") !== -1) {
  65147. codecSupportedFound = true;
  65148. }
  65149. if (codecSupportedFound) {
  65150. // Loading sound using XHR2
  65151. if (!this._streaming) {
  65152. this._scene._loadFile(url, function (data) {
  65153. _this._soundLoaded(data);
  65154. }, undefined, true, true, function (exception) {
  65155. if (exception) {
  65156. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  65157. }
  65158. BABYLON.Tools.Error("Sound creation aborted.");
  65159. _this._scene.mainSoundTrack.RemoveSound(_this);
  65160. });
  65161. }
  65162. // Streaming sound using HTML5 Audio tag
  65163. else {
  65164. this._htmlAudioElement = new Audio(url);
  65165. this._htmlAudioElement.controls = false;
  65166. this._htmlAudioElement.loop = this.loop;
  65167. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  65168. this._htmlAudioElement.preload = "auto";
  65169. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  65170. _this._isReadyToPlay = true;
  65171. if (_this.autoplay) {
  65172. _this.play();
  65173. }
  65174. if (_this._readyToPlayCallback) {
  65175. _this._readyToPlayCallback();
  65176. }
  65177. });
  65178. document.body.appendChild(this._htmlAudioElement);
  65179. }
  65180. break;
  65181. }
  65182. }
  65183. break;
  65184. default:
  65185. validParameter = false;
  65186. break;
  65187. }
  65188. if (!validParameter) {
  65189. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  65190. }
  65191. else {
  65192. if (!codecSupportedFound) {
  65193. this._isReadyToPlay = true;
  65194. // Simulating a ready to play event to avoid breaking code path
  65195. if (this._readyToPlayCallback) {
  65196. window.setTimeout(function () {
  65197. if (_this._readyToPlayCallback) {
  65198. _this._readyToPlayCallback();
  65199. }
  65200. }, 1000);
  65201. }
  65202. }
  65203. }
  65204. }
  65205. catch (ex) {
  65206. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  65207. this._scene.mainSoundTrack.RemoveSound(this);
  65208. }
  65209. }
  65210. }
  65211. else {
  65212. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  65213. this._scene.mainSoundTrack.AddSound(this);
  65214. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  65215. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  65216. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  65217. }
  65218. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  65219. if (this._readyToPlayCallback) {
  65220. window.setTimeout(function () {
  65221. if (_this._readyToPlayCallback) {
  65222. _this._readyToPlayCallback();
  65223. }
  65224. }, 1000);
  65225. }
  65226. }
  65227. }
  65228. Sound.prototype.dispose = function () {
  65229. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65230. if (this.isPlaying) {
  65231. this.stop();
  65232. }
  65233. this._isReadyToPlay = false;
  65234. if (this.soundTrackId === -1) {
  65235. this._scene.mainSoundTrack.RemoveSound(this);
  65236. }
  65237. else {
  65238. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  65239. }
  65240. if (this._soundGain) {
  65241. this._soundGain.disconnect();
  65242. this._soundGain = null;
  65243. }
  65244. if (this._soundPanner) {
  65245. this._soundPanner.disconnect();
  65246. this._soundPanner = null;
  65247. }
  65248. if (this._soundSource) {
  65249. this._soundSource.disconnect();
  65250. this._soundSource = null;
  65251. }
  65252. this._audioBuffer = null;
  65253. if (this._htmlAudioElement) {
  65254. this._htmlAudioElement.pause();
  65255. this._htmlAudioElement.src = "";
  65256. document.body.removeChild(this._htmlAudioElement);
  65257. }
  65258. if (this._streamingSource) {
  65259. this._streamingSource.disconnect();
  65260. }
  65261. if (this._connectedMesh && this._registerFunc) {
  65262. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65263. this._connectedMesh = null;
  65264. }
  65265. }
  65266. };
  65267. Sound.prototype.isReady = function () {
  65268. return this._isReadyToPlay;
  65269. };
  65270. Sound.prototype._soundLoaded = function (audioData) {
  65271. var _this = this;
  65272. if (!BABYLON.Engine.audioEngine.audioContext) {
  65273. return;
  65274. }
  65275. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  65276. _this._audioBuffer = buffer;
  65277. _this._isReadyToPlay = true;
  65278. if (_this.autoplay) {
  65279. _this.play();
  65280. }
  65281. if (_this._readyToPlayCallback) {
  65282. _this._readyToPlayCallback();
  65283. }
  65284. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  65285. };
  65286. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  65287. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65288. this._audioBuffer = audioBuffer;
  65289. this._isReadyToPlay = true;
  65290. }
  65291. };
  65292. Sound.prototype.updateOptions = function (options) {
  65293. if (options) {
  65294. this.loop = options.loop || this.loop;
  65295. this.maxDistance = options.maxDistance || this.maxDistance;
  65296. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  65297. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  65298. this.refDistance = options.refDistance || this.refDistance;
  65299. this.distanceModel = options.distanceModel || this.distanceModel;
  65300. this._playbackRate = options.playbackRate || this._playbackRate;
  65301. this._updateSpatialParameters();
  65302. if (this.isPlaying) {
  65303. if (this._streaming && this._htmlAudioElement) {
  65304. this._htmlAudioElement.playbackRate = this._playbackRate;
  65305. }
  65306. else {
  65307. if (this._soundSource) {
  65308. this._soundSource.playbackRate.value = this._playbackRate;
  65309. }
  65310. }
  65311. }
  65312. }
  65313. };
  65314. Sound.prototype._createSpatialParameters = function () {
  65315. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65316. if (this._scene.headphone) {
  65317. this._panningModel = "HRTF";
  65318. }
  65319. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  65320. this._updateSpatialParameters();
  65321. this._soundPanner.connect(this._outputAudioNode);
  65322. this._inputAudioNode = this._soundPanner;
  65323. }
  65324. };
  65325. Sound.prototype._updateSpatialParameters = function () {
  65326. if (this.spatialSound && this._soundPanner) {
  65327. if (this.useCustomAttenuation) {
  65328. // Tricks to disable in a way embedded Web Audio attenuation
  65329. this._soundPanner.distanceModel = "linear";
  65330. this._soundPanner.maxDistance = Number.MAX_VALUE;
  65331. this._soundPanner.refDistance = 1;
  65332. this._soundPanner.rolloffFactor = 1;
  65333. this._soundPanner.panningModel = this._panningModel;
  65334. }
  65335. else {
  65336. this._soundPanner.distanceModel = this.distanceModel;
  65337. this._soundPanner.maxDistance = this.maxDistance;
  65338. this._soundPanner.refDistance = this.refDistance;
  65339. this._soundPanner.rolloffFactor = this.rolloffFactor;
  65340. this._soundPanner.panningModel = this._panningModel;
  65341. }
  65342. }
  65343. };
  65344. Sound.prototype.switchPanningModelToHRTF = function () {
  65345. this._panningModel = "HRTF";
  65346. this._switchPanningModel();
  65347. };
  65348. Sound.prototype.switchPanningModelToEqualPower = function () {
  65349. this._panningModel = "equalpower";
  65350. this._switchPanningModel();
  65351. };
  65352. Sound.prototype._switchPanningModel = function () {
  65353. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  65354. this._soundPanner.panningModel = this._panningModel;
  65355. }
  65356. };
  65357. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  65358. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65359. if (this._isOutputConnected) {
  65360. this._outputAudioNode.disconnect();
  65361. }
  65362. this._outputAudioNode.connect(soundTrackAudioNode);
  65363. this._isOutputConnected = true;
  65364. }
  65365. };
  65366. /**
  65367. * Transform this sound into a directional source
  65368. * @param coneInnerAngle Size of the inner cone in degree
  65369. * @param coneOuterAngle Size of the outer cone in degree
  65370. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  65371. */
  65372. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  65373. if (coneOuterAngle < coneInnerAngle) {
  65374. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  65375. return;
  65376. }
  65377. this._coneInnerAngle = coneInnerAngle;
  65378. this._coneOuterAngle = coneOuterAngle;
  65379. this._coneOuterGain = coneOuterGain;
  65380. this._isDirectional = true;
  65381. if (this.isPlaying && this.loop) {
  65382. this.stop();
  65383. this.play();
  65384. }
  65385. };
  65386. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  65387. /**
  65388. * Gets or sets the inner angle for the directional cone.
  65389. */
  65390. get: function () {
  65391. return this._coneInnerAngle;
  65392. },
  65393. /**
  65394. * Gets or sets the inner angle for the directional cone.
  65395. */
  65396. set: function (value) {
  65397. if (value != this._coneInnerAngle) {
  65398. if (this._coneOuterAngle < value) {
  65399. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65400. return;
  65401. }
  65402. this._coneInnerAngle = value;
  65403. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  65404. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  65405. }
  65406. }
  65407. },
  65408. enumerable: true,
  65409. configurable: true
  65410. });
  65411. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  65412. /**
  65413. * Gets or sets the outer angle for the directional cone.
  65414. */
  65415. get: function () {
  65416. return this._coneOuterAngle;
  65417. },
  65418. /**
  65419. * Gets or sets the outer angle for the directional cone.
  65420. */
  65421. set: function (value) {
  65422. if (value != this._coneOuterAngle) {
  65423. if (value < this._coneInnerAngle) {
  65424. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65425. return;
  65426. }
  65427. this._coneOuterAngle = value;
  65428. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  65429. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  65430. }
  65431. }
  65432. },
  65433. enumerable: true,
  65434. configurable: true
  65435. });
  65436. Sound.prototype.setPosition = function (newPosition) {
  65437. this._position = newPosition;
  65438. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  65439. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  65440. }
  65441. };
  65442. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  65443. this._localDirection = newLocalDirection;
  65444. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  65445. this._updateDirection();
  65446. }
  65447. };
  65448. Sound.prototype._updateDirection = function () {
  65449. if (!this._connectedMesh || !this._soundPanner) {
  65450. return;
  65451. }
  65452. var mat = this._connectedMesh.getWorldMatrix();
  65453. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  65454. direction.normalize();
  65455. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  65456. };
  65457. Sound.prototype.updateDistanceFromListener = function () {
  65458. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  65459. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  65460. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  65461. }
  65462. };
  65463. Sound.prototype.setAttenuationFunction = function (callback) {
  65464. this._customAttenuationFunction = callback;
  65465. };
  65466. /**
  65467. * Play the sound
  65468. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  65469. * @param offset (optional) Start the sound setting it at a specific time
  65470. */
  65471. Sound.prototype.play = function (time, offset) {
  65472. var _this = this;
  65473. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  65474. try {
  65475. if (this._startOffset < 0) {
  65476. time = -this._startOffset;
  65477. this._startOffset = 0;
  65478. }
  65479. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  65480. if (!this._soundSource || !this._streamingSource) {
  65481. if (this.spatialSound && this._soundPanner) {
  65482. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  65483. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  65484. }
  65485. if (this._isDirectional) {
  65486. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  65487. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  65488. this._soundPanner.coneOuterGain = this._coneOuterGain;
  65489. if (this._connectedMesh) {
  65490. this._updateDirection();
  65491. }
  65492. else {
  65493. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  65494. }
  65495. }
  65496. }
  65497. }
  65498. if (this._streaming) {
  65499. if (!this._streamingSource) {
  65500. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  65501. this._htmlAudioElement.onended = function () { _this._onended(); };
  65502. this._htmlAudioElement.playbackRate = this._playbackRate;
  65503. }
  65504. this._streamingSource.disconnect();
  65505. this._streamingSource.connect(this._inputAudioNode);
  65506. if (this._htmlAudioElement) {
  65507. this._htmlAudioElement.play();
  65508. }
  65509. }
  65510. else {
  65511. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  65512. this._soundSource.buffer = this._audioBuffer;
  65513. this._soundSource.connect(this._inputAudioNode);
  65514. this._soundSource.loop = this.loop;
  65515. this._soundSource.playbackRate.value = this._playbackRate;
  65516. this._soundSource.onended = function () { _this._onended(); };
  65517. if (this._soundSource.buffer) {
  65518. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  65519. }
  65520. }
  65521. this._startTime = startTime;
  65522. this.isPlaying = true;
  65523. this.isPaused = false;
  65524. }
  65525. catch (ex) {
  65526. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  65527. }
  65528. }
  65529. };
  65530. Sound.prototype._onended = function () {
  65531. this.isPlaying = false;
  65532. if (this.onended) {
  65533. this.onended();
  65534. }
  65535. this.onEndedObservable.notifyObservers(this);
  65536. };
  65537. /**
  65538. * Stop the sound
  65539. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  65540. */
  65541. Sound.prototype.stop = function (time) {
  65542. if (this.isPlaying) {
  65543. if (this._streaming) {
  65544. if (this._htmlAudioElement) {
  65545. this._htmlAudioElement.pause();
  65546. // Test needed for Firefox or it will generate an Invalid State Error
  65547. if (this._htmlAudioElement.currentTime > 0) {
  65548. this._htmlAudioElement.currentTime = 0;
  65549. }
  65550. }
  65551. else {
  65552. this._streamingSource.disconnect();
  65553. }
  65554. }
  65555. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  65556. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  65557. this._soundSource.stop(stopTime);
  65558. this._soundSource.onended = function () { };
  65559. if (!this.isPaused) {
  65560. this._startOffset = 0;
  65561. }
  65562. }
  65563. this.isPlaying = false;
  65564. }
  65565. };
  65566. Sound.prototype.pause = function () {
  65567. if (this.isPlaying) {
  65568. this.isPaused = true;
  65569. if (this._streaming) {
  65570. if (this._htmlAudioElement) {
  65571. this._htmlAudioElement.pause();
  65572. }
  65573. else {
  65574. this._streamingSource.disconnect();
  65575. }
  65576. }
  65577. else if (BABYLON.Engine.audioEngine.audioContext) {
  65578. this.stop(0);
  65579. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  65580. }
  65581. }
  65582. };
  65583. Sound.prototype.setVolume = function (newVolume, time) {
  65584. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  65585. if (time && BABYLON.Engine.audioEngine.audioContext) {
  65586. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  65587. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  65588. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  65589. }
  65590. else {
  65591. this._soundGain.gain.value = newVolume;
  65592. }
  65593. }
  65594. this._volume = newVolume;
  65595. };
  65596. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  65597. this._playbackRate = newPlaybackRate;
  65598. if (this.isPlaying) {
  65599. if (this._streaming && this._htmlAudioElement) {
  65600. this._htmlAudioElement.playbackRate = this._playbackRate;
  65601. }
  65602. else if (this._soundSource) {
  65603. this._soundSource.playbackRate.value = this._playbackRate;
  65604. }
  65605. }
  65606. };
  65607. Sound.prototype.getVolume = function () {
  65608. return this._volume;
  65609. };
  65610. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  65611. var _this = this;
  65612. if (this._connectedMesh && this._registerFunc) {
  65613. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65614. this._registerFunc = null;
  65615. }
  65616. this._connectedMesh = meshToConnectTo;
  65617. if (!this.spatialSound) {
  65618. this.spatialSound = true;
  65619. this._createSpatialParameters();
  65620. if (this.isPlaying && this.loop) {
  65621. this.stop();
  65622. this.play();
  65623. }
  65624. }
  65625. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  65626. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  65627. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  65628. };
  65629. Sound.prototype.detachFromMesh = function () {
  65630. if (this._connectedMesh && this._registerFunc) {
  65631. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65632. this._registerFunc = null;
  65633. this._connectedMesh = null;
  65634. }
  65635. };
  65636. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  65637. if (!node.getBoundingInfo) {
  65638. return;
  65639. }
  65640. var mesh = node;
  65641. if (this._positionInEmitterSpace) {
  65642. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  65643. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  65644. }
  65645. else {
  65646. var boundingInfo = mesh.getBoundingInfo();
  65647. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  65648. }
  65649. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  65650. this._updateDirection();
  65651. }
  65652. };
  65653. Sound.prototype.clone = function () {
  65654. var _this = this;
  65655. if (!this._streaming) {
  65656. var setBufferAndRun = function () {
  65657. if (_this._isReadyToPlay) {
  65658. clonedSound._audioBuffer = _this.getAudioBuffer();
  65659. clonedSound._isReadyToPlay = true;
  65660. if (clonedSound.autoplay) {
  65661. clonedSound.play();
  65662. }
  65663. }
  65664. else {
  65665. window.setTimeout(setBufferAndRun, 300);
  65666. }
  65667. };
  65668. var currentOptions = {
  65669. autoplay: this.autoplay, loop: this.loop,
  65670. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  65671. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  65672. refDistance: this.refDistance, distanceModel: this.distanceModel
  65673. };
  65674. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  65675. if (this.useCustomAttenuation) {
  65676. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  65677. }
  65678. clonedSound.setPosition(this._position);
  65679. clonedSound.setPlaybackRate(this._playbackRate);
  65680. setBufferAndRun();
  65681. return clonedSound;
  65682. }
  65683. // Can't clone a streaming sound
  65684. else {
  65685. return null;
  65686. }
  65687. };
  65688. Sound.prototype.getAudioBuffer = function () {
  65689. return this._audioBuffer;
  65690. };
  65691. Sound.prototype.serialize = function () {
  65692. var serializationObject = {
  65693. name: this.name,
  65694. url: this.name,
  65695. autoplay: this.autoplay,
  65696. loop: this.loop,
  65697. volume: this._volume,
  65698. spatialSound: this.spatialSound,
  65699. maxDistance: this.maxDistance,
  65700. rolloffFactor: this.rolloffFactor,
  65701. refDistance: this.refDistance,
  65702. distanceModel: this.distanceModel,
  65703. playbackRate: this._playbackRate,
  65704. panningModel: this._panningModel,
  65705. soundTrackId: this.soundTrackId
  65706. };
  65707. if (this.spatialSound) {
  65708. if (this._connectedMesh)
  65709. serializationObject.connectedMeshId = this._connectedMesh.id;
  65710. serializationObject.position = this._position.asArray();
  65711. serializationObject.refDistance = this.refDistance;
  65712. serializationObject.distanceModel = this.distanceModel;
  65713. serializationObject.isDirectional = this._isDirectional;
  65714. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  65715. serializationObject.coneInnerAngle = this._coneInnerAngle;
  65716. serializationObject.coneOuterAngle = this._coneOuterAngle;
  65717. serializationObject.coneOuterGain = this._coneOuterGain;
  65718. }
  65719. return serializationObject;
  65720. };
  65721. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  65722. var soundName = parsedSound.name;
  65723. var soundUrl;
  65724. if (parsedSound.url) {
  65725. soundUrl = rootUrl + parsedSound.url;
  65726. }
  65727. else {
  65728. soundUrl = rootUrl + soundName;
  65729. }
  65730. var options = {
  65731. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  65732. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  65733. rolloffFactor: parsedSound.rolloffFactor,
  65734. refDistance: parsedSound.refDistance,
  65735. distanceModel: parsedSound.distanceModel,
  65736. playbackRate: parsedSound.playbackRate
  65737. };
  65738. var newSound;
  65739. if (!sourceSound) {
  65740. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  65741. scene._addPendingData(newSound);
  65742. }
  65743. else {
  65744. var setBufferAndRun = function () {
  65745. if (sourceSound._isReadyToPlay) {
  65746. newSound._audioBuffer = sourceSound.getAudioBuffer();
  65747. newSound._isReadyToPlay = true;
  65748. if (newSound.autoplay) {
  65749. newSound.play();
  65750. }
  65751. }
  65752. else {
  65753. window.setTimeout(setBufferAndRun, 300);
  65754. }
  65755. };
  65756. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  65757. setBufferAndRun();
  65758. }
  65759. if (parsedSound.position) {
  65760. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  65761. newSound.setPosition(soundPosition);
  65762. }
  65763. if (parsedSound.isDirectional) {
  65764. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  65765. if (parsedSound.localDirectionToMesh) {
  65766. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  65767. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  65768. }
  65769. }
  65770. if (parsedSound.connectedMeshId) {
  65771. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  65772. if (connectedMesh) {
  65773. newSound.attachToMesh(connectedMesh);
  65774. }
  65775. }
  65776. return newSound;
  65777. };
  65778. return Sound;
  65779. }());
  65780. BABYLON.Sound = Sound;
  65781. })(BABYLON || (BABYLON = {}));
  65782. //# sourceMappingURL=babylon.sound.js.map
  65783. var BABYLON;
  65784. (function (BABYLON) {
  65785. var SoundTrack = /** @class */ (function () {
  65786. function SoundTrack(scene, options) {
  65787. this.id = -1;
  65788. this._isMainTrack = false;
  65789. this._isInitialized = false;
  65790. this._scene = scene;
  65791. this.soundCollection = new Array();
  65792. this._options = options;
  65793. if (!this._isMainTrack) {
  65794. this._scene.soundTracks.push(this);
  65795. this.id = this._scene.soundTracks.length - 1;
  65796. }
  65797. }
  65798. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  65799. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65800. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  65801. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  65802. if (this._options) {
  65803. if (this._options.volume) {
  65804. this._outputAudioNode.gain.value = this._options.volume;
  65805. }
  65806. if (this._options.mainTrack) {
  65807. this._isMainTrack = this._options.mainTrack;
  65808. }
  65809. }
  65810. this._isInitialized = true;
  65811. }
  65812. };
  65813. SoundTrack.prototype.dispose = function () {
  65814. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  65815. if (this._connectedAnalyser) {
  65816. this._connectedAnalyser.stopDebugCanvas();
  65817. }
  65818. while (this.soundCollection.length) {
  65819. this.soundCollection[0].dispose();
  65820. }
  65821. if (this._outputAudioNode) {
  65822. this._outputAudioNode.disconnect();
  65823. }
  65824. this._outputAudioNode = null;
  65825. }
  65826. };
  65827. SoundTrack.prototype.AddSound = function (sound) {
  65828. if (!this._isInitialized) {
  65829. this._initializeSoundTrackAudioGraph();
  65830. }
  65831. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  65832. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  65833. }
  65834. if (sound.soundTrackId) {
  65835. if (sound.soundTrackId === -1) {
  65836. this._scene.mainSoundTrack.RemoveSound(sound);
  65837. }
  65838. else {
  65839. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  65840. }
  65841. }
  65842. this.soundCollection.push(sound);
  65843. sound.soundTrackId = this.id;
  65844. };
  65845. SoundTrack.prototype.RemoveSound = function (sound) {
  65846. var index = this.soundCollection.indexOf(sound);
  65847. if (index !== -1) {
  65848. this.soundCollection.splice(index, 1);
  65849. }
  65850. };
  65851. SoundTrack.prototype.setVolume = function (newVolume) {
  65852. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  65853. this._outputAudioNode.gain.value = newVolume;
  65854. }
  65855. };
  65856. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  65857. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65858. for (var i = 0; i < this.soundCollection.length; i++) {
  65859. this.soundCollection[i].switchPanningModelToHRTF();
  65860. }
  65861. }
  65862. };
  65863. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  65864. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65865. for (var i = 0; i < this.soundCollection.length; i++) {
  65866. this.soundCollection[i].switchPanningModelToEqualPower();
  65867. }
  65868. }
  65869. };
  65870. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  65871. if (this._connectedAnalyser) {
  65872. this._connectedAnalyser.stopDebugCanvas();
  65873. }
  65874. this._connectedAnalyser = analyser;
  65875. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  65876. this._outputAudioNode.disconnect();
  65877. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  65878. }
  65879. };
  65880. return SoundTrack;
  65881. }());
  65882. BABYLON.SoundTrack = SoundTrack;
  65883. })(BABYLON || (BABYLON = {}));
  65884. //# sourceMappingURL=babylon.soundtrack.js.map
  65885. var BABYLON;
  65886. (function (BABYLON) {
  65887. /**
  65888. * Class used to work with sound analyzer using fast fourier transform (FFT)
  65889. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  65890. */
  65891. var Analyser = /** @class */ (function () {
  65892. /**
  65893. * Creates a new analyser
  65894. * @param scene defines hosting scene
  65895. */
  65896. function Analyser(scene) {
  65897. /**
  65898. * Gets or sets the smoothing
  65899. * @ignorenaming
  65900. */
  65901. this.SMOOTHING = 0.75;
  65902. /**
  65903. * Gets or sets the FFT table size
  65904. * @ignorenaming
  65905. */
  65906. this.FFT_SIZE = 512;
  65907. /**
  65908. * Gets or sets the bar graph amplitude
  65909. * @ignorenaming
  65910. */
  65911. this.BARGRAPHAMPLITUDE = 256;
  65912. /**
  65913. * Gets or sets the position of the debug canvas
  65914. * @ignorenaming
  65915. */
  65916. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  65917. /**
  65918. * Gets or sets the debug canvas size
  65919. * @ignorenaming
  65920. */
  65921. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  65922. this._scene = scene;
  65923. this._audioEngine = BABYLON.Engine.audioEngine;
  65924. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  65925. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  65926. this._webAudioAnalyser.minDecibels = -140;
  65927. this._webAudioAnalyser.maxDecibels = 0;
  65928. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  65929. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  65930. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  65931. }
  65932. }
  65933. /**
  65934. * Get the number of data values you will have to play with for the visualization
  65935. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  65936. * @returns a number
  65937. */
  65938. Analyser.prototype.getFrequencyBinCount = function () {
  65939. if (this._audioEngine.canUseWebAudio) {
  65940. return this._webAudioAnalyser.frequencyBinCount;
  65941. }
  65942. else {
  65943. return 0;
  65944. }
  65945. };
  65946. /**
  65947. * Gets the current frequency data as a byte array
  65948. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  65949. * @returns a Uint8Array
  65950. */
  65951. Analyser.prototype.getByteFrequencyData = function () {
  65952. if (this._audioEngine.canUseWebAudio) {
  65953. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65954. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65955. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  65956. }
  65957. return this._byteFreqs;
  65958. };
  65959. /**
  65960. * Gets the current waveform as a byte array
  65961. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  65962. * @returns a Uint8Array
  65963. */
  65964. Analyser.prototype.getByteTimeDomainData = function () {
  65965. if (this._audioEngine.canUseWebAudio) {
  65966. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65967. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65968. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  65969. }
  65970. return this._byteTime;
  65971. };
  65972. /**
  65973. * Gets the current frequency data as a float array
  65974. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  65975. * @returns a Float32Array
  65976. */
  65977. Analyser.prototype.getFloatFrequencyData = function () {
  65978. if (this._audioEngine.canUseWebAudio) {
  65979. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65980. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65981. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  65982. }
  65983. return this._floatFreqs;
  65984. };
  65985. /**
  65986. * Renders the debug canvas
  65987. */
  65988. Analyser.prototype.drawDebugCanvas = function () {
  65989. var _this = this;
  65990. if (this._audioEngine.canUseWebAudio) {
  65991. if (!this._debugCanvas) {
  65992. this._debugCanvas = document.createElement("canvas");
  65993. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  65994. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  65995. this._debugCanvas.style.position = "absolute";
  65996. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  65997. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  65998. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  65999. document.body.appendChild(this._debugCanvas);
  66000. this._registerFunc = function () {
  66001. _this.drawDebugCanvas();
  66002. };
  66003. this._scene.registerBeforeRender(this._registerFunc);
  66004. }
  66005. if (this._registerFunc && this._debugCanvasContext) {
  66006. var workingArray = this.getByteFrequencyData();
  66007. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  66008. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  66009. // Draw the frequency domain chart.
  66010. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  66011. var value = workingArray[i];
  66012. var percent = value / this.BARGRAPHAMPLITUDE;
  66013. var height = this.DEBUGCANVASSIZE.height * percent;
  66014. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  66015. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  66016. var hue = i / this.getFrequencyBinCount() * 360;
  66017. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  66018. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  66019. }
  66020. }
  66021. }
  66022. };
  66023. /**
  66024. * Stops rendering the debug canvas and removes it
  66025. */
  66026. Analyser.prototype.stopDebugCanvas = function () {
  66027. if (this._debugCanvas) {
  66028. if (this._registerFunc) {
  66029. this._scene.unregisterBeforeRender(this._registerFunc);
  66030. this._registerFunc = null;
  66031. }
  66032. document.body.removeChild(this._debugCanvas);
  66033. this._debugCanvas = null;
  66034. this._debugCanvasContext = null;
  66035. }
  66036. };
  66037. /**
  66038. * Connects two audio nodes
  66039. * @param inputAudioNode defines first node to connect
  66040. * @param outputAudioNode defines second node to connect
  66041. */
  66042. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  66043. if (this._audioEngine.canUseWebAudio) {
  66044. inputAudioNode.connect(this._webAudioAnalyser);
  66045. this._webAudioAnalyser.connect(outputAudioNode);
  66046. }
  66047. };
  66048. /**
  66049. * Releases all associated resources
  66050. */
  66051. Analyser.prototype.dispose = function () {
  66052. if (this._audioEngine.canUseWebAudio) {
  66053. this._webAudioAnalyser.disconnect();
  66054. }
  66055. };
  66056. return Analyser;
  66057. }());
  66058. BABYLON.Analyser = Analyser;
  66059. })(BABYLON || (BABYLON = {}));
  66060. //# sourceMappingURL=babylon.analyser.js.map
  66061. var BABYLON;
  66062. (function (BABYLON) {
  66063. /**
  66064. * Wraps one or more Sound objects and selects one with random weight for playback.
  66065. */
  66066. var WeightedSound = /** @class */ (function () {
  66067. /**
  66068. * Creates a new WeightedSound from the list of sounds given.
  66069. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  66070. * @param sounds Array of Sounds that will be selected from.
  66071. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  66072. */
  66073. function WeightedSound(loop, sounds, weights) {
  66074. var _this = this;
  66075. /** When true a Sound will be selected and played when the current playing Sound completes. */
  66076. this.loop = false;
  66077. this._coneInnerAngle = 360;
  66078. this._coneOuterAngle = 360;
  66079. this._volume = 1;
  66080. /** A Sound is currently playing. */
  66081. this.isPlaying = false;
  66082. /** A Sound is currently paused. */
  66083. this.isPaused = false;
  66084. this._sounds = [];
  66085. this._weights = [];
  66086. if (sounds.length !== weights.length) {
  66087. throw new Error('Sounds length does not equal weights length');
  66088. }
  66089. this.loop = loop;
  66090. this._weights = weights;
  66091. // Normalize the weights
  66092. var weightSum = 0;
  66093. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  66094. var weight = weights_1[_i];
  66095. weightSum += weight;
  66096. }
  66097. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  66098. for (var i = 0; i < this._weights.length; i++) {
  66099. this._weights[i] *= invWeightSum;
  66100. }
  66101. this._sounds = sounds;
  66102. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  66103. var sound = _b[_a];
  66104. sound.onEndedObservable.add(function () { _this._onended(); });
  66105. }
  66106. }
  66107. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  66108. /**
  66109. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  66110. */
  66111. get: function () {
  66112. return this._coneInnerAngle;
  66113. },
  66114. /**
  66115. * The size of cone in degress for a directional sound in which there will be no attenuation.
  66116. */
  66117. set: function (value) {
  66118. if (value !== this._coneInnerAngle) {
  66119. if (this._coneOuterAngle < value) {
  66120. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66121. return;
  66122. }
  66123. this._coneInnerAngle = value;
  66124. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66125. var sound = _a[_i];
  66126. sound.directionalConeInnerAngle = value;
  66127. }
  66128. }
  66129. },
  66130. enumerable: true,
  66131. configurable: true
  66132. });
  66133. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  66134. /**
  66135. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  66136. * Listener angles between innerAngle and outerAngle will falloff linearly.
  66137. */
  66138. get: function () {
  66139. return this._coneOuterAngle;
  66140. },
  66141. /**
  66142. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  66143. * Listener angles between innerAngle and outerAngle will falloff linearly.
  66144. */
  66145. set: function (value) {
  66146. if (value !== this._coneOuterAngle) {
  66147. if (value < this._coneInnerAngle) {
  66148. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66149. return;
  66150. }
  66151. this._coneOuterAngle = value;
  66152. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66153. var sound = _a[_i];
  66154. sound.directionalConeOuterAngle = value;
  66155. }
  66156. }
  66157. },
  66158. enumerable: true,
  66159. configurable: true
  66160. });
  66161. Object.defineProperty(WeightedSound.prototype, "volume", {
  66162. /**
  66163. * Playback volume.
  66164. */
  66165. get: function () {
  66166. return this._volume;
  66167. },
  66168. /**
  66169. * Playback volume.
  66170. */
  66171. set: function (value) {
  66172. if (value !== this._volume) {
  66173. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66174. var sound = _a[_i];
  66175. sound.setVolume(value);
  66176. }
  66177. }
  66178. },
  66179. enumerable: true,
  66180. configurable: true
  66181. });
  66182. WeightedSound.prototype._onended = function () {
  66183. if (this._currentIndex !== undefined) {
  66184. this._sounds[this._currentIndex].autoplay = false;
  66185. }
  66186. if (this.loop && this.isPlaying) {
  66187. this.play();
  66188. }
  66189. else {
  66190. this.isPlaying = false;
  66191. }
  66192. };
  66193. /**
  66194. * Suspend playback
  66195. */
  66196. WeightedSound.prototype.pause = function () {
  66197. this.isPaused = true;
  66198. if (this._currentIndex !== undefined) {
  66199. this._sounds[this._currentIndex].pause();
  66200. }
  66201. };
  66202. /**
  66203. * Stop playback
  66204. */
  66205. WeightedSound.prototype.stop = function () {
  66206. this.isPlaying = false;
  66207. if (this._currentIndex !== undefined) {
  66208. this._sounds[this._currentIndex].stop();
  66209. }
  66210. };
  66211. /**
  66212. * Start playback.
  66213. * @param startOffset Position the clip head at a specific time in seconds.
  66214. */
  66215. WeightedSound.prototype.play = function (startOffset) {
  66216. if (!this.isPaused) {
  66217. this.stop();
  66218. var randomValue = Math.random();
  66219. var total = 0;
  66220. for (var i = 0; i < this._weights.length; i++) {
  66221. total += this._weights[i];
  66222. if (randomValue <= total) {
  66223. this._currentIndex = i;
  66224. break;
  66225. }
  66226. }
  66227. }
  66228. var sound = this._sounds[this._currentIndex];
  66229. if (sound.isReady()) {
  66230. sound.play(0, this.isPaused ? undefined : startOffset);
  66231. }
  66232. else {
  66233. sound.autoplay = true;
  66234. }
  66235. this.isPlaying = true;
  66236. this.isPaused = false;
  66237. };
  66238. return WeightedSound;
  66239. }());
  66240. BABYLON.WeightedSound = WeightedSound;
  66241. })(BABYLON || (BABYLON = {}));
  66242. //# sourceMappingURL=babylon.weightedsound.js.map
  66243. var BABYLON;
  66244. (function (BABYLON) {
  66245. var CubeTexture = /** @class */ (function (_super) {
  66246. __extends(CubeTexture, _super);
  66247. /**
  66248. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  66249. * as prefiltered data.
  66250. * @param rootUrl defines the url of the texture or the root name of the six images
  66251. * @param scene defines the scene the texture is attached to
  66252. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  66253. * @param noMipmap defines if mipmaps should be created or not
  66254. * @param files defines the six files to load for the different faces
  66255. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  66256. * @param onError defines a callback triggered in case of error during load
  66257. * @param format defines the internal format to use for the texture once loaded
  66258. * @param prefiltered defines whether or not the texture is created from prefiltered data
  66259. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  66260. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  66261. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  66262. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  66263. * @return the cube texture
  66264. */
  66265. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  66266. if (extensions === void 0) { extensions = null; }
  66267. if (noMipmap === void 0) { noMipmap = false; }
  66268. if (files === void 0) { files = null; }
  66269. if (onLoad === void 0) { onLoad = null; }
  66270. if (onError === void 0) { onError = null; }
  66271. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66272. if (prefiltered === void 0) { prefiltered = false; }
  66273. if (forcedExtension === void 0) { forcedExtension = null; }
  66274. if (createPolynomials === void 0) { createPolynomials = false; }
  66275. if (lodScale === void 0) { lodScale = 0.8; }
  66276. if (lodOffset === void 0) { lodOffset = 0; }
  66277. var _this = _super.call(this, scene) || this;
  66278. /**
  66279. * Gets or sets the center of the bounding box associated with the cube texture
  66280. * It must define where the camera used to render the texture was set
  66281. */
  66282. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  66283. _this._rotationY = 0;
  66284. /** @hidden */
  66285. _this._prefiltered = false;
  66286. _this.name = rootUrl;
  66287. _this.url = rootUrl;
  66288. _this._noMipmap = noMipmap;
  66289. _this.hasAlpha = false;
  66290. _this._format = format;
  66291. _this.isCube = true;
  66292. _this._textureMatrix = BABYLON.Matrix.Identity();
  66293. _this._createPolynomials = createPolynomials;
  66294. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  66295. if (!rootUrl && !files) {
  66296. return _this;
  66297. }
  66298. var lastDot = rootUrl.lastIndexOf(".");
  66299. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  66300. var isDDS = (extension === ".dds");
  66301. var isEnv = (extension === ".env");
  66302. if (isEnv) {
  66303. _this.gammaSpace = false;
  66304. _this._prefiltered = false;
  66305. }
  66306. else {
  66307. _this._prefiltered = prefiltered;
  66308. if (prefiltered) {
  66309. _this.gammaSpace = false;
  66310. }
  66311. }
  66312. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  66313. if (!files) {
  66314. if (!isEnv && !isDDS && !extensions) {
  66315. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  66316. }
  66317. files = [];
  66318. if (extensions) {
  66319. for (var index = 0; index < extensions.length; index++) {
  66320. files.push(rootUrl + extensions[index]);
  66321. }
  66322. }
  66323. }
  66324. _this._files = files;
  66325. if (!_this._texture) {
  66326. if (!scene.useDelayedTextureLoading) {
  66327. if (prefiltered) {
  66328. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  66329. }
  66330. else {
  66331. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  66332. }
  66333. }
  66334. else {
  66335. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  66336. }
  66337. }
  66338. else if (onLoad) {
  66339. if (_this._texture.isReady) {
  66340. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  66341. }
  66342. else {
  66343. _this._texture.onLoadedObservable.add(onLoad);
  66344. }
  66345. }
  66346. return _this;
  66347. }
  66348. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  66349. get: function () {
  66350. return this._boundingBoxSize;
  66351. },
  66352. /**
  66353. * Gets or sets the size of the bounding box associated with the cube texture
  66354. * When defined, the cubemap will switch to local mode
  66355. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  66356. * @example https://www.babylonjs-playground.com/#RNASML
  66357. */
  66358. set: function (value) {
  66359. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  66360. return;
  66361. }
  66362. this._boundingBoxSize = value;
  66363. var scene = this.getScene();
  66364. if (scene) {
  66365. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  66366. }
  66367. },
  66368. enumerable: true,
  66369. configurable: true
  66370. });
  66371. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  66372. /**
  66373. * Gets texture matrix rotation angle around Y axis radians.
  66374. */
  66375. get: function () {
  66376. return this._rotationY;
  66377. },
  66378. /**
  66379. * Sets texture matrix rotation angle around Y axis in radians.
  66380. */
  66381. set: function (value) {
  66382. this._rotationY = value;
  66383. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  66384. },
  66385. enumerable: true,
  66386. configurable: true
  66387. });
  66388. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  66389. var rootUrlKey = "";
  66390. files.forEach(function (url) { return rootUrlKey += url; });
  66391. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  66392. };
  66393. /**
  66394. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  66395. * @param url defines the url of the prefiltered texture
  66396. * @param scene defines the scene the texture is attached to
  66397. * @param forcedExtension defines the extension of the file if different from the url
  66398. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  66399. * @return the prefiltered texture
  66400. */
  66401. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  66402. if (forcedExtension === void 0) { forcedExtension = null; }
  66403. if (createPolynomials === void 0) { createPolynomials = true; }
  66404. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  66405. };
  66406. // Methods
  66407. CubeTexture.prototype.delayLoad = function () {
  66408. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  66409. return;
  66410. }
  66411. var scene = this.getScene();
  66412. if (!scene) {
  66413. return;
  66414. }
  66415. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  66416. this._texture = this._getFromCache(this.url, this._noMipmap);
  66417. if (!this._texture) {
  66418. if (this._prefiltered) {
  66419. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  66420. }
  66421. else {
  66422. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  66423. }
  66424. }
  66425. };
  66426. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  66427. return this._textureMatrix;
  66428. };
  66429. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  66430. this._textureMatrix = value;
  66431. };
  66432. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  66433. var texture = BABYLON.SerializationHelper.Parse(function () {
  66434. var prefiltered = false;
  66435. if (parsedTexture.prefiltered) {
  66436. prefiltered = parsedTexture.prefiltered;
  66437. }
  66438. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  66439. }, parsedTexture, scene);
  66440. // Local Cubemaps
  66441. if (parsedTexture.boundingBoxPosition) {
  66442. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  66443. }
  66444. if (parsedTexture.boundingBoxSize) {
  66445. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  66446. }
  66447. // Animations
  66448. if (parsedTexture.animations) {
  66449. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  66450. var parsedAnimation = parsedTexture.animations[animationIndex];
  66451. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  66452. }
  66453. }
  66454. return texture;
  66455. };
  66456. CubeTexture.prototype.clone = function () {
  66457. var _this = this;
  66458. return BABYLON.SerializationHelper.Clone(function () {
  66459. var scene = _this.getScene();
  66460. if (!scene) {
  66461. return _this;
  66462. }
  66463. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  66464. }, this);
  66465. };
  66466. __decorate([
  66467. BABYLON.serialize("rotationY")
  66468. ], CubeTexture.prototype, "rotationY", null);
  66469. return CubeTexture;
  66470. }(BABYLON.BaseTexture));
  66471. BABYLON.CubeTexture = CubeTexture;
  66472. })(BABYLON || (BABYLON = {}));
  66473. //# sourceMappingURL=babylon.cubeTexture.js.map
  66474. var BABYLON;
  66475. (function (BABYLON) {
  66476. /**
  66477. * Raw cube texture where the raw buffers are passed in
  66478. */
  66479. var RawCubeTexture = /** @class */ (function (_super) {
  66480. __extends(RawCubeTexture, _super);
  66481. /**
  66482. * Creates a cube texture where the raw buffers are passed in.
  66483. * @param scene defines the scene the texture is attached to
  66484. * @param data defines the array of data to use to create each face
  66485. * @param size defines the size of the textures
  66486. * @param format defines the format of the data
  66487. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  66488. * @param generateMipMaps defines if the engine should generate the mip levels
  66489. * @param invertY defines if data must be stored with Y axis inverted
  66490. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  66491. * @param compression defines the compression used (null by default)
  66492. */
  66493. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  66494. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66495. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66496. if (generateMipMaps === void 0) { generateMipMaps = false; }
  66497. if (invertY === void 0) { invertY = false; }
  66498. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66499. if (compression === void 0) { compression = null; }
  66500. var _this = _super.call(this, "", scene) || this;
  66501. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  66502. return _this;
  66503. }
  66504. /**
  66505. * Updates the raw cube texture.
  66506. * @param data defines the data to store
  66507. * @param format defines the data format
  66508. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  66509. * @param invertY defines if data must be stored with Y axis inverted
  66510. * @param compression defines the compression used (null by default)
  66511. * @param level defines which level of the texture to update
  66512. */
  66513. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  66514. if (compression === void 0) { compression = null; }
  66515. if (level === void 0) { level = 0; }
  66516. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  66517. };
  66518. /**
  66519. * Updates a raw cube texture with RGBD encoded data.
  66520. * @param data defines the array of data [mipmap][face] to use to create each face
  66521. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  66522. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  66523. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  66524. * @returns a promsie that resolves when the operation is complete
  66525. */
  66526. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  66527. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  66528. if (lodScale === void 0) { lodScale = 0.8; }
  66529. if (lodOffset === void 0) { lodOffset = 0; }
  66530. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  66531. };
  66532. /**
  66533. * Clones the raw cube texture.
  66534. * @return a new cube texture
  66535. */
  66536. RawCubeTexture.prototype.clone = function () {
  66537. var _this = this;
  66538. return BABYLON.SerializationHelper.Clone(function () {
  66539. var scene = _this.getScene();
  66540. var internalTexture = _this._texture;
  66541. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  66542. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  66543. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  66544. }
  66545. return texture;
  66546. }, this);
  66547. };
  66548. /** @hidden */
  66549. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  66550. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  66551. internalTexture._bufferViewArrayArray = data;
  66552. internalTexture._lodGenerationScale = lodScale;
  66553. internalTexture._lodGenerationOffset = lodOffset;
  66554. internalTexture._sphericalPolynomial = sphericalPolynomial;
  66555. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  66556. internalTexture.isReady = true;
  66557. });
  66558. };
  66559. return RawCubeTexture;
  66560. }(BABYLON.CubeTexture));
  66561. BABYLON.RawCubeTexture = RawCubeTexture;
  66562. })(BABYLON || (BABYLON = {}));
  66563. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  66564. var BABYLON;
  66565. (function (BABYLON) {
  66566. var RenderTargetTexture = /** @class */ (function (_super) {
  66567. __extends(RenderTargetTexture, _super);
  66568. /**
  66569. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  66570. * or used a shadow, depth texture...
  66571. * @param name The friendly name of the texture
  66572. * @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)
  66573. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  66574. * @param generateMipMaps True if mip maps need to be generated after render.
  66575. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  66576. * @param type The type of the buffer in the RTT (int, half float, float...)
  66577. * @param isCube True if a cube texture needs to be created
  66578. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  66579. * @param generateDepthBuffer True to generate a depth buffer
  66580. * @param generateStencilBuffer True to generate a stencil buffer
  66581. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  66582. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  66583. */
  66584. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  66585. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  66586. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66587. if (isCube === void 0) { isCube = false; }
  66588. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66589. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  66590. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  66591. if (isMulti === void 0) { isMulti = false; }
  66592. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66593. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  66594. _this.isCube = isCube;
  66595. _this.renderParticles = true;
  66596. _this.renderSprites = false;
  66597. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  66598. _this.ignoreCameraViewport = false;
  66599. // Events
  66600. /**
  66601. * An event triggered when the texture is unbind.
  66602. */
  66603. _this.onBeforeBindObservable = new BABYLON.Observable();
  66604. /**
  66605. * An event triggered when the texture is unbind.
  66606. */
  66607. _this.onAfterUnbindObservable = new BABYLON.Observable();
  66608. /**
  66609. * An event triggered before rendering the texture
  66610. */
  66611. _this.onBeforeRenderObservable = new BABYLON.Observable();
  66612. /**
  66613. * An event triggered after rendering the texture
  66614. */
  66615. _this.onAfterRenderObservable = new BABYLON.Observable();
  66616. /**
  66617. * An event triggered after the texture clear
  66618. */
  66619. _this.onClearObservable = new BABYLON.Observable();
  66620. _this._currentRefreshId = -1;
  66621. _this._refreshRate = 1;
  66622. _this._samples = 1;
  66623. /**
  66624. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  66625. * It must define where the camera used to render the texture is set
  66626. */
  66627. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  66628. scene = _this.getScene();
  66629. if (!scene) {
  66630. return _this;
  66631. }
  66632. _this.renderList = new Array();
  66633. _this._engine = scene.getEngine();
  66634. _this.name = name;
  66635. _this.isRenderTarget = true;
  66636. _this._initialSizeParameter = size;
  66637. _this._processSizeParameter(size);
  66638. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  66639. });
  66640. _this._generateMipMaps = generateMipMaps ? true : false;
  66641. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  66642. // Rendering groups
  66643. _this._renderingManager = new BABYLON.RenderingManager(scene);
  66644. _this._renderingManager._useSceneAutoClearSetup = true;
  66645. if (isMulti) {
  66646. return _this;
  66647. }
  66648. _this._renderTargetOptions = {
  66649. generateMipMaps: generateMipMaps,
  66650. type: type,
  66651. format: format,
  66652. samplingMode: samplingMode,
  66653. generateDepthBuffer: generateDepthBuffer,
  66654. generateStencilBuffer: generateStencilBuffer
  66655. };
  66656. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  66657. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66658. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66659. }
  66660. if (isCube) {
  66661. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  66662. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  66663. _this._textureMatrix = BABYLON.Matrix.Identity();
  66664. }
  66665. else {
  66666. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  66667. }
  66668. return _this;
  66669. }
  66670. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  66671. get: function () {
  66672. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  66673. },
  66674. enumerable: true,
  66675. configurable: true
  66676. });
  66677. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  66678. get: function () {
  66679. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  66680. },
  66681. enumerable: true,
  66682. configurable: true
  66683. });
  66684. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  66685. get: function () {
  66686. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  66687. },
  66688. enumerable: true,
  66689. configurable: true
  66690. });
  66691. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  66692. /**
  66693. * Use this list to define the list of mesh you want to render.
  66694. */
  66695. get: function () {
  66696. return this._renderList;
  66697. },
  66698. set: function (value) {
  66699. this._renderList = value;
  66700. if (this._renderList) {
  66701. this._hookArray(this._renderList);
  66702. }
  66703. },
  66704. enumerable: true,
  66705. configurable: true
  66706. });
  66707. RenderTargetTexture.prototype._hookArray = function (array) {
  66708. var _this = this;
  66709. var oldPush = array.push;
  66710. array.push = function () {
  66711. var items = [];
  66712. for (var _i = 0; _i < arguments.length; _i++) {
  66713. items[_i] = arguments[_i];
  66714. }
  66715. var result = oldPush.apply(array, items);
  66716. _this.getScene().meshes.forEach(function (mesh) {
  66717. mesh._markSubMeshesAsLightDirty();
  66718. });
  66719. return result;
  66720. };
  66721. var oldSplice = array.splice;
  66722. array.splice = function (index, deleteCount) {
  66723. var deleted = oldSplice.apply(array, [index, deleteCount]);
  66724. _this.getScene().meshes.forEach(function (mesh) {
  66725. mesh._markSubMeshesAsLightDirty();
  66726. });
  66727. return deleted;
  66728. };
  66729. };
  66730. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  66731. set: function (callback) {
  66732. if (this._onAfterUnbindObserver) {
  66733. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  66734. }
  66735. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  66736. },
  66737. enumerable: true,
  66738. configurable: true
  66739. });
  66740. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  66741. set: function (callback) {
  66742. if (this._onBeforeRenderObserver) {
  66743. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  66744. }
  66745. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  66746. },
  66747. enumerable: true,
  66748. configurable: true
  66749. });
  66750. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  66751. set: function (callback) {
  66752. if (this._onAfterRenderObserver) {
  66753. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  66754. }
  66755. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  66756. },
  66757. enumerable: true,
  66758. configurable: true
  66759. });
  66760. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  66761. set: function (callback) {
  66762. if (this._onClearObserver) {
  66763. this.onClearObservable.remove(this._onClearObserver);
  66764. }
  66765. this._onClearObserver = this.onClearObservable.add(callback);
  66766. },
  66767. enumerable: true,
  66768. configurable: true
  66769. });
  66770. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  66771. get: function () {
  66772. return this._renderTargetOptions;
  66773. },
  66774. enumerable: true,
  66775. configurable: true
  66776. });
  66777. RenderTargetTexture.prototype._onRatioRescale = function () {
  66778. if (this._sizeRatio) {
  66779. this.resize(this._initialSizeParameter);
  66780. }
  66781. };
  66782. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  66783. get: function () {
  66784. return this._boundingBoxSize;
  66785. },
  66786. /**
  66787. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  66788. * When defined, the cubemap will switch to local mode
  66789. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  66790. * @example https://www.babylonjs-playground.com/#RNASML
  66791. */
  66792. set: function (value) {
  66793. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  66794. return;
  66795. }
  66796. this._boundingBoxSize = value;
  66797. var scene = this.getScene();
  66798. if (scene) {
  66799. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  66800. }
  66801. },
  66802. enumerable: true,
  66803. configurable: true
  66804. });
  66805. /**
  66806. * Creates a depth stencil texture.
  66807. * This is only available in WebGL 2 or with the depth texture extension available.
  66808. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  66809. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  66810. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  66811. */
  66812. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  66813. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  66814. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  66815. if (generateStencil === void 0) { generateStencil = false; }
  66816. if (!this.getScene()) {
  66817. return;
  66818. }
  66819. var engine = this.getScene().getEngine();
  66820. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  66821. bilinearFiltering: bilinearFiltering,
  66822. comparisonFunction: comparisonFunction,
  66823. generateStencil: generateStencil,
  66824. isCube: this.isCube
  66825. });
  66826. engine.setFrameBufferDepthStencilTexture(this);
  66827. };
  66828. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  66829. if (size.ratio) {
  66830. this._sizeRatio = size.ratio;
  66831. this._size = {
  66832. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  66833. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  66834. };
  66835. }
  66836. else {
  66837. this._size = size;
  66838. }
  66839. };
  66840. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  66841. get: function () {
  66842. return this._samples;
  66843. },
  66844. set: function (value) {
  66845. if (this._samples === value) {
  66846. return;
  66847. }
  66848. var scene = this.getScene();
  66849. if (!scene) {
  66850. return;
  66851. }
  66852. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  66853. },
  66854. enumerable: true,
  66855. configurable: true
  66856. });
  66857. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  66858. this._currentRefreshId = -1;
  66859. };
  66860. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  66861. get: function () {
  66862. return this._refreshRate;
  66863. },
  66864. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  66865. set: function (value) {
  66866. this._refreshRate = value;
  66867. this.resetRefreshCounter();
  66868. },
  66869. enumerable: true,
  66870. configurable: true
  66871. });
  66872. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  66873. if (!this._postProcessManager) {
  66874. var scene = this.getScene();
  66875. if (!scene) {
  66876. return;
  66877. }
  66878. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  66879. this._postProcesses = new Array();
  66880. }
  66881. this._postProcesses.push(postProcess);
  66882. this._postProcesses[0].autoClear = false;
  66883. };
  66884. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  66885. if (!this._postProcesses) {
  66886. return;
  66887. }
  66888. if (dispose) {
  66889. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  66890. var postProcess = _a[_i];
  66891. postProcess.dispose();
  66892. }
  66893. }
  66894. this._postProcesses = [];
  66895. };
  66896. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  66897. if (!this._postProcesses) {
  66898. return;
  66899. }
  66900. var index = this._postProcesses.indexOf(postProcess);
  66901. if (index === -1) {
  66902. return;
  66903. }
  66904. this._postProcesses.splice(index, 1);
  66905. if (this._postProcesses.length > 0) {
  66906. this._postProcesses[0].autoClear = false;
  66907. }
  66908. };
  66909. /** @hidden */
  66910. RenderTargetTexture.prototype._shouldRender = function () {
  66911. if (this._currentRefreshId === -1) { // At least render once
  66912. this._currentRefreshId = 1;
  66913. return true;
  66914. }
  66915. if (this.refreshRate === this._currentRefreshId) {
  66916. this._currentRefreshId = 1;
  66917. return true;
  66918. }
  66919. this._currentRefreshId++;
  66920. return false;
  66921. };
  66922. RenderTargetTexture.prototype.getRenderSize = function () {
  66923. if (this._size.width) {
  66924. return this._size.width;
  66925. }
  66926. return this._size;
  66927. };
  66928. RenderTargetTexture.prototype.getRenderWidth = function () {
  66929. if (this._size.width) {
  66930. return this._size.width;
  66931. }
  66932. return this._size;
  66933. };
  66934. RenderTargetTexture.prototype.getRenderHeight = function () {
  66935. if (this._size.width) {
  66936. return this._size.height;
  66937. }
  66938. return this._size;
  66939. };
  66940. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  66941. get: function () {
  66942. return true;
  66943. },
  66944. enumerable: true,
  66945. configurable: true
  66946. });
  66947. RenderTargetTexture.prototype.scale = function (ratio) {
  66948. var newSize = this.getRenderSize() * ratio;
  66949. this.resize(newSize);
  66950. };
  66951. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  66952. if (this.isCube) {
  66953. return this._textureMatrix;
  66954. }
  66955. return _super.prototype.getReflectionTextureMatrix.call(this);
  66956. };
  66957. RenderTargetTexture.prototype.resize = function (size) {
  66958. this.releaseInternalTexture();
  66959. var scene = this.getScene();
  66960. if (!scene) {
  66961. return;
  66962. }
  66963. this._processSizeParameter(size);
  66964. if (this.isCube) {
  66965. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  66966. }
  66967. else {
  66968. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  66969. }
  66970. };
  66971. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  66972. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  66973. if (dumpForDebug === void 0) { dumpForDebug = false; }
  66974. var scene = this.getScene();
  66975. if (!scene) {
  66976. return;
  66977. }
  66978. var engine = scene.getEngine();
  66979. if (this.useCameraPostProcesses !== undefined) {
  66980. useCameraPostProcess = this.useCameraPostProcesses;
  66981. }
  66982. if (this._waitingRenderList) {
  66983. this.renderList = [];
  66984. for (var index = 0; index < this._waitingRenderList.length; index++) {
  66985. var id = this._waitingRenderList[index];
  66986. var mesh_1 = scene.getMeshByID(id);
  66987. if (mesh_1) {
  66988. this.renderList.push(mesh_1);
  66989. }
  66990. }
  66991. delete this._waitingRenderList;
  66992. }
  66993. // Is predicate defined?
  66994. if (this.renderListPredicate) {
  66995. if (this.renderList) {
  66996. this.renderList.splice(0); // Clear previous renderList
  66997. }
  66998. else {
  66999. this.renderList = [];
  67000. }
  67001. var scene = this.getScene();
  67002. if (!scene) {
  67003. return;
  67004. }
  67005. var sceneMeshes = scene.meshes;
  67006. for (var index = 0; index < sceneMeshes.length; index++) {
  67007. var mesh = sceneMeshes[index];
  67008. if (this.renderListPredicate(mesh)) {
  67009. this.renderList.push(mesh);
  67010. }
  67011. }
  67012. }
  67013. this.onBeforeBindObservable.notifyObservers(this);
  67014. // Set custom projection.
  67015. // Needs to be before binding to prevent changing the aspect ratio.
  67016. var camera;
  67017. if (this.activeCamera) {
  67018. camera = this.activeCamera;
  67019. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  67020. if (this.activeCamera !== scene.activeCamera) {
  67021. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  67022. }
  67023. }
  67024. else {
  67025. camera = scene.activeCamera;
  67026. if (camera) {
  67027. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  67028. }
  67029. }
  67030. // Prepare renderingManager
  67031. this._renderingManager.reset();
  67032. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  67033. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  67034. var sceneRenderId = scene.getRenderId();
  67035. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  67036. var mesh = currentRenderList[meshIndex];
  67037. if (mesh) {
  67038. if (!mesh.isReady(this.refreshRate === 0)) {
  67039. this.resetRefreshCounter();
  67040. continue;
  67041. }
  67042. mesh._preActivateForIntermediateRendering(sceneRenderId);
  67043. var isMasked = void 0;
  67044. if (!this.renderList && camera) {
  67045. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  67046. }
  67047. else {
  67048. isMasked = false;
  67049. }
  67050. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  67051. mesh._activate(sceneRenderId);
  67052. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  67053. var subMesh = mesh.subMeshes[subIndex];
  67054. scene._activeIndices.addCount(subMesh.indexCount, false);
  67055. this._renderingManager.dispatch(subMesh, mesh);
  67056. }
  67057. }
  67058. }
  67059. }
  67060. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  67061. var particleSystem = scene.particleSystems[particleIndex];
  67062. var emitter = particleSystem.emitter;
  67063. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  67064. continue;
  67065. }
  67066. if (currentRenderList.indexOf(emitter) >= 0) {
  67067. this._renderingManager.dispatchParticles(particleSystem);
  67068. }
  67069. }
  67070. if (this.isCube) {
  67071. for (var face = 0; face < 6; face++) {
  67072. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  67073. scene.incrementRenderId();
  67074. scene.resetCachedMaterial();
  67075. }
  67076. }
  67077. else {
  67078. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  67079. }
  67080. this.onAfterUnbindObservable.notifyObservers(this);
  67081. if (scene.activeCamera) {
  67082. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  67083. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  67084. }
  67085. engine.setViewport(scene.activeCamera.viewport);
  67086. }
  67087. scene.resetCachedMaterial();
  67088. };
  67089. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  67090. var minimum = 128;
  67091. var x = renderDimension * scale;
  67092. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  67093. // Ensure we don't exceed the render dimension (while staying POT)
  67094. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  67095. };
  67096. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  67097. var _this = this;
  67098. if (!this._texture) {
  67099. return;
  67100. }
  67101. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  67102. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  67103. });
  67104. };
  67105. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  67106. var scene = this.getScene();
  67107. if (!scene) {
  67108. return;
  67109. }
  67110. var engine = scene.getEngine();
  67111. if (!this._texture) {
  67112. return;
  67113. }
  67114. // Bind
  67115. if (this._postProcessManager) {
  67116. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  67117. }
  67118. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  67119. if (this._texture) {
  67120. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  67121. }
  67122. }
  67123. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  67124. // Clear
  67125. if (this.onClearObservable.hasObservers()) {
  67126. this.onClearObservable.notifyObservers(engine);
  67127. }
  67128. else {
  67129. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  67130. }
  67131. if (!this._doNotChangeAspectRatio) {
  67132. scene.updateTransformMatrix(true);
  67133. }
  67134. // Render
  67135. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  67136. if (this._postProcessManager) {
  67137. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  67138. }
  67139. else if (useCameraPostProcess) {
  67140. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  67141. }
  67142. if (!this._doNotChangeAspectRatio) {
  67143. scene.updateTransformMatrix(true);
  67144. }
  67145. // Dump ?
  67146. if (dumpForDebug) {
  67147. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  67148. }
  67149. // Unbind
  67150. if (!this.isCube || faceIndex === 5) {
  67151. if (this.isCube) {
  67152. if (faceIndex === 5) {
  67153. engine.generateMipMapsForCubemap(this._texture);
  67154. }
  67155. }
  67156. this.unbindFrameBuffer(engine, faceIndex);
  67157. }
  67158. else {
  67159. this.onAfterRenderObservable.notifyObservers(faceIndex);
  67160. }
  67161. };
  67162. /**
  67163. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  67164. * This allowed control for front to back rendering or reversly depending of the special needs.
  67165. *
  67166. * @param renderingGroupId The rendering group id corresponding to its index
  67167. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  67168. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  67169. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  67170. */
  67171. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  67172. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  67173. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  67174. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  67175. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  67176. };
  67177. /**
  67178. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  67179. *
  67180. * @param renderingGroupId The rendering group id corresponding to its index
  67181. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  67182. */
  67183. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  67184. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  67185. this._renderingManager._useSceneAutoClearSetup = false;
  67186. };
  67187. RenderTargetTexture.prototype.clone = function () {
  67188. var textureSize = this.getSize();
  67189. 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);
  67190. // Base texture
  67191. newTexture.hasAlpha = this.hasAlpha;
  67192. newTexture.level = this.level;
  67193. // RenderTarget Texture
  67194. newTexture.coordinatesMode = this.coordinatesMode;
  67195. if (this.renderList) {
  67196. newTexture.renderList = this.renderList.slice(0);
  67197. }
  67198. return newTexture;
  67199. };
  67200. RenderTargetTexture.prototype.serialize = function () {
  67201. if (!this.name) {
  67202. return null;
  67203. }
  67204. var serializationObject = _super.prototype.serialize.call(this);
  67205. serializationObject.renderTargetSize = this.getRenderSize();
  67206. serializationObject.renderList = [];
  67207. if (this.renderList) {
  67208. for (var index = 0; index < this.renderList.length; index++) {
  67209. serializationObject.renderList.push(this.renderList[index].id);
  67210. }
  67211. }
  67212. return serializationObject;
  67213. };
  67214. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  67215. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  67216. var objBuffer = this.getInternalTexture();
  67217. var scene = this.getScene();
  67218. if (objBuffer && scene) {
  67219. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  67220. }
  67221. };
  67222. RenderTargetTexture.prototype.dispose = function () {
  67223. if (this._postProcessManager) {
  67224. this._postProcessManager.dispose();
  67225. this._postProcessManager = null;
  67226. }
  67227. this.clearPostProcesses(true);
  67228. if (this._resizeObserver) {
  67229. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  67230. this._resizeObserver = null;
  67231. }
  67232. this.renderList = null;
  67233. // Remove from custom render targets
  67234. var scene = this.getScene();
  67235. if (!scene) {
  67236. return;
  67237. }
  67238. var index = scene.customRenderTargets.indexOf(this);
  67239. if (index >= 0) {
  67240. scene.customRenderTargets.splice(index, 1);
  67241. }
  67242. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  67243. var camera = _a[_i];
  67244. index = camera.customRenderTargets.indexOf(this);
  67245. if (index >= 0) {
  67246. camera.customRenderTargets.splice(index, 1);
  67247. }
  67248. }
  67249. _super.prototype.dispose.call(this);
  67250. };
  67251. /** @hidden */
  67252. RenderTargetTexture.prototype._rebuild = function () {
  67253. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  67254. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  67255. }
  67256. if (this._postProcessManager) {
  67257. this._postProcessManager._rebuild();
  67258. }
  67259. };
  67260. /**
  67261. * Clear the info related to rendering groups preventing retention point in material dispose.
  67262. */
  67263. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  67264. if (this._renderingManager) {
  67265. this._renderingManager.freeRenderingGroups();
  67266. }
  67267. };
  67268. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  67269. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  67270. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  67271. return RenderTargetTexture;
  67272. }(BABYLON.Texture));
  67273. BABYLON.RenderTargetTexture = RenderTargetTexture;
  67274. })(BABYLON || (BABYLON = {}));
  67275. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  67276. var BABYLON;
  67277. (function (BABYLON) {
  67278. ;
  67279. var MultiRenderTarget = /** @class */ (function (_super) {
  67280. __extends(MultiRenderTarget, _super);
  67281. function MultiRenderTarget(name, size, count, scene, options) {
  67282. var _this = this;
  67283. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  67284. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  67285. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  67286. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  67287. _this._engine = scene.getEngine();
  67288. if (!_this.isSupported) {
  67289. _this.dispose();
  67290. return;
  67291. }
  67292. var types = [];
  67293. var samplingModes = [];
  67294. for (var i = 0; i < count; i++) {
  67295. if (options && options.types && options.types[i] !== undefined) {
  67296. types.push(options.types[i]);
  67297. }
  67298. else {
  67299. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67300. }
  67301. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  67302. samplingModes.push(options.samplingModes[i]);
  67303. }
  67304. else {
  67305. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67306. }
  67307. }
  67308. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  67309. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  67310. _this._size = size;
  67311. _this._multiRenderTargetOptions = {
  67312. samplingModes: samplingModes,
  67313. generateMipMaps: generateMipMaps,
  67314. generateDepthBuffer: generateDepthBuffer,
  67315. generateStencilBuffer: generateStencilBuffer,
  67316. generateDepthTexture: generateDepthTexture,
  67317. types: types,
  67318. textureCount: count
  67319. };
  67320. _this._createInternalTextures();
  67321. _this._createTextures();
  67322. return _this;
  67323. }
  67324. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  67325. get: function () {
  67326. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  67327. },
  67328. enumerable: true,
  67329. configurable: true
  67330. });
  67331. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  67332. get: function () {
  67333. return this._textures;
  67334. },
  67335. enumerable: true,
  67336. configurable: true
  67337. });
  67338. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  67339. get: function () {
  67340. return this._textures[this._textures.length - 1];
  67341. },
  67342. enumerable: true,
  67343. configurable: true
  67344. });
  67345. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  67346. set: function (wrap) {
  67347. if (this._textures) {
  67348. for (var i = 0; i < this._textures.length; i++) {
  67349. this._textures[i].wrapU = wrap;
  67350. }
  67351. }
  67352. },
  67353. enumerable: true,
  67354. configurable: true
  67355. });
  67356. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  67357. set: function (wrap) {
  67358. if (this._textures) {
  67359. for (var i = 0; i < this._textures.length; i++) {
  67360. this._textures[i].wrapV = wrap;
  67361. }
  67362. }
  67363. },
  67364. enumerable: true,
  67365. configurable: true
  67366. });
  67367. /** @hidden */
  67368. MultiRenderTarget.prototype._rebuild = function () {
  67369. this.releaseInternalTextures();
  67370. this._createInternalTextures();
  67371. for (var i = 0; i < this._internalTextures.length; i++) {
  67372. var texture = this._textures[i];
  67373. texture._texture = this._internalTextures[i];
  67374. }
  67375. // Keeps references to frame buffer and stencil/depth buffer
  67376. this._texture = this._internalTextures[0];
  67377. };
  67378. MultiRenderTarget.prototype._createInternalTextures = function () {
  67379. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  67380. };
  67381. MultiRenderTarget.prototype._createTextures = function () {
  67382. this._textures = [];
  67383. for (var i = 0; i < this._internalTextures.length; i++) {
  67384. var texture = new BABYLON.Texture(null, this.getScene());
  67385. texture._texture = this._internalTextures[i];
  67386. this._textures.push(texture);
  67387. }
  67388. // Keeps references to frame buffer and stencil/depth buffer
  67389. this._texture = this._internalTextures[0];
  67390. };
  67391. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  67392. get: function () {
  67393. return this._samples;
  67394. },
  67395. set: function (value) {
  67396. if (this._samples === value) {
  67397. return;
  67398. }
  67399. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  67400. },
  67401. enumerable: true,
  67402. configurable: true
  67403. });
  67404. MultiRenderTarget.prototype.resize = function (size) {
  67405. this.releaseInternalTextures();
  67406. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  67407. this._createInternalTextures();
  67408. };
  67409. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  67410. var _this = this;
  67411. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  67412. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  67413. });
  67414. };
  67415. MultiRenderTarget.prototype.dispose = function () {
  67416. this.releaseInternalTextures();
  67417. _super.prototype.dispose.call(this);
  67418. };
  67419. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  67420. if (!this._internalTextures) {
  67421. return;
  67422. }
  67423. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  67424. if (this._internalTextures[i] !== undefined) {
  67425. this._internalTextures[i].dispose();
  67426. this._internalTextures.splice(i, 1);
  67427. }
  67428. }
  67429. };
  67430. return MultiRenderTarget;
  67431. }(BABYLON.RenderTargetTexture));
  67432. BABYLON.MultiRenderTarget = MultiRenderTarget;
  67433. })(BABYLON || (BABYLON = {}));
  67434. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  67435. var BABYLON;
  67436. (function (BABYLON) {
  67437. var MirrorTexture = /** @class */ (function (_super) {
  67438. __extends(MirrorTexture, _super);
  67439. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  67440. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67441. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67442. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  67443. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  67444. _this.scene = scene;
  67445. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  67446. _this._transformMatrix = BABYLON.Matrix.Zero();
  67447. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  67448. _this._adaptiveBlurKernel = 0;
  67449. _this._blurKernelX = 0;
  67450. _this._blurKernelY = 0;
  67451. _this._blurRatio = 1.0;
  67452. _this.ignoreCameraViewport = true;
  67453. _this._updateGammaSpace();
  67454. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  67455. _this._updateGammaSpace;
  67456. });
  67457. _this.onBeforeRenderObservable.add(function () {
  67458. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  67459. _this._savedViewMatrix = scene.getViewMatrix();
  67460. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  67461. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  67462. scene.clipPlane = _this.mirrorPlane;
  67463. scene.getEngine().cullBackFaces = false;
  67464. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  67465. });
  67466. _this.onAfterRenderObservable.add(function () {
  67467. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  67468. scene.getEngine().cullBackFaces = true;
  67469. scene._mirroredCameraPosition = null;
  67470. delete scene.clipPlane;
  67471. });
  67472. return _this;
  67473. }
  67474. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  67475. get: function () {
  67476. return this._blurRatio;
  67477. },
  67478. set: function (value) {
  67479. if (this._blurRatio === value) {
  67480. return;
  67481. }
  67482. this._blurRatio = value;
  67483. this._preparePostProcesses();
  67484. },
  67485. enumerable: true,
  67486. configurable: true
  67487. });
  67488. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  67489. set: function (value) {
  67490. this._adaptiveBlurKernel = value;
  67491. this._autoComputeBlurKernel();
  67492. },
  67493. enumerable: true,
  67494. configurable: true
  67495. });
  67496. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  67497. set: function (value) {
  67498. this.blurKernelX = value;
  67499. this.blurKernelY = value;
  67500. },
  67501. enumerable: true,
  67502. configurable: true
  67503. });
  67504. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  67505. get: function () {
  67506. return this._blurKernelX;
  67507. },
  67508. set: function (value) {
  67509. if (this._blurKernelX === value) {
  67510. return;
  67511. }
  67512. this._blurKernelX = value;
  67513. this._preparePostProcesses();
  67514. },
  67515. enumerable: true,
  67516. configurable: true
  67517. });
  67518. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  67519. get: function () {
  67520. return this._blurKernelY;
  67521. },
  67522. set: function (value) {
  67523. if (this._blurKernelY === value) {
  67524. return;
  67525. }
  67526. this._blurKernelY = value;
  67527. this._preparePostProcesses();
  67528. },
  67529. enumerable: true,
  67530. configurable: true
  67531. });
  67532. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  67533. var engine = this.getScene().getEngine();
  67534. var dw = this.getRenderWidth() / engine.getRenderWidth();
  67535. var dh = this.getRenderHeight() / engine.getRenderHeight();
  67536. this.blurKernelX = this._adaptiveBlurKernel * dw;
  67537. this.blurKernelY = this._adaptiveBlurKernel * dh;
  67538. };
  67539. MirrorTexture.prototype._onRatioRescale = function () {
  67540. if (this._sizeRatio) {
  67541. this.resize(this._initialSizeParameter);
  67542. if (!this._adaptiveBlurKernel) {
  67543. this._preparePostProcesses();
  67544. }
  67545. }
  67546. if (this._adaptiveBlurKernel) {
  67547. this._autoComputeBlurKernel();
  67548. }
  67549. };
  67550. MirrorTexture.prototype._updateGammaSpace = function () {
  67551. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  67552. };
  67553. MirrorTexture.prototype._preparePostProcesses = function () {
  67554. this.clearPostProcesses(true);
  67555. if (this._blurKernelX && this._blurKernelY) {
  67556. var engine = this.getScene().getEngine();
  67557. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67558. 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);
  67559. this._blurX.autoClear = false;
  67560. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  67561. this._blurX.inputTexture = this._texture;
  67562. }
  67563. else {
  67564. this._blurX.alwaysForcePOT = true;
  67565. }
  67566. 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);
  67567. this._blurY.autoClear = false;
  67568. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  67569. this.addPostProcess(this._blurX);
  67570. this.addPostProcess(this._blurY);
  67571. }
  67572. else {
  67573. if (this._blurY) {
  67574. this.removePostProcess(this._blurY);
  67575. this._blurY.dispose();
  67576. this._blurY = null;
  67577. }
  67578. if (this._blurX) {
  67579. this.removePostProcess(this._blurX);
  67580. this._blurX.dispose();
  67581. this._blurX = null;
  67582. }
  67583. }
  67584. };
  67585. MirrorTexture.prototype.clone = function () {
  67586. var scene = this.getScene();
  67587. if (!scene) {
  67588. return this;
  67589. }
  67590. var textureSize = this.getSize();
  67591. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  67592. // Base texture
  67593. newTexture.hasAlpha = this.hasAlpha;
  67594. newTexture.level = this.level;
  67595. // Mirror Texture
  67596. newTexture.mirrorPlane = this.mirrorPlane.clone();
  67597. if (this.renderList) {
  67598. newTexture.renderList = this.renderList.slice(0);
  67599. }
  67600. return newTexture;
  67601. };
  67602. MirrorTexture.prototype.serialize = function () {
  67603. if (!this.name) {
  67604. return null;
  67605. }
  67606. var serializationObject = _super.prototype.serialize.call(this);
  67607. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  67608. return serializationObject;
  67609. };
  67610. MirrorTexture.prototype.dispose = function () {
  67611. _super.prototype.dispose.call(this);
  67612. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  67613. };
  67614. return MirrorTexture;
  67615. }(BABYLON.RenderTargetTexture));
  67616. BABYLON.MirrorTexture = MirrorTexture;
  67617. })(BABYLON || (BABYLON = {}));
  67618. //# sourceMappingURL=babylon.mirrorTexture.js.map
  67619. var BABYLON;
  67620. (function (BABYLON) {
  67621. /**
  67622. * Creates a refraction texture used by refraction channel of the standard material.
  67623. * @param name the texture name
  67624. * @param size size of the underlying texture
  67625. * @param scene root scene
  67626. */
  67627. var RefractionTexture = /** @class */ (function (_super) {
  67628. __extends(RefractionTexture, _super);
  67629. function RefractionTexture(name, size, scene, generateMipMaps) {
  67630. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  67631. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  67632. _this.depth = 2.0;
  67633. _this.onBeforeRenderObservable.add(function () {
  67634. scene.clipPlane = _this.refractionPlane;
  67635. });
  67636. _this.onAfterRenderObservable.add(function () {
  67637. delete scene.clipPlane;
  67638. });
  67639. return _this;
  67640. }
  67641. RefractionTexture.prototype.clone = function () {
  67642. var scene = this.getScene();
  67643. if (!scene) {
  67644. return this;
  67645. }
  67646. var textureSize = this.getSize();
  67647. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  67648. // Base texture
  67649. newTexture.hasAlpha = this.hasAlpha;
  67650. newTexture.level = this.level;
  67651. // Refraction Texture
  67652. newTexture.refractionPlane = this.refractionPlane.clone();
  67653. if (this.renderList) {
  67654. newTexture.renderList = this.renderList.slice(0);
  67655. }
  67656. newTexture.depth = this.depth;
  67657. return newTexture;
  67658. };
  67659. RefractionTexture.prototype.serialize = function () {
  67660. if (!this.name) {
  67661. return null;
  67662. }
  67663. var serializationObject = _super.prototype.serialize.call(this);
  67664. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  67665. serializationObject.depth = this.depth;
  67666. return serializationObject;
  67667. };
  67668. return RefractionTexture;
  67669. }(BABYLON.RenderTargetTexture));
  67670. BABYLON.RefractionTexture = RefractionTexture;
  67671. })(BABYLON || (BABYLON = {}));
  67672. //# sourceMappingURL=babylon.refractionTexture.js.map
  67673. var BABYLON;
  67674. (function (BABYLON) {
  67675. /**
  67676. * A class extending {BABYLON.Texture} allowing drawing on a texture
  67677. * @see http://doc.babylonjs.com/how_to/dynamictexture
  67678. */
  67679. var DynamicTexture = /** @class */ (function (_super) {
  67680. __extends(DynamicTexture, _super);
  67681. /**
  67682. * Creates a {BABYLON.DynamicTexture}
  67683. * @param name defines the name of the texture
  67684. * @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
  67685. * @param scene defines the scene where you want the texture
  67686. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  67687. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  67688. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  67689. */
  67690. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  67691. if (scene === void 0) { scene = null; }
  67692. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67693. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67694. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  67695. _this.name = name;
  67696. _this._engine = _this.getScene().getEngine();
  67697. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67698. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67699. _this._generateMipMaps = generateMipMaps;
  67700. if (options.getContext) {
  67701. _this._canvas = options;
  67702. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  67703. }
  67704. else {
  67705. _this._canvas = document.createElement("canvas");
  67706. if (options.width || options.width === 0) {
  67707. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  67708. }
  67709. else {
  67710. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  67711. }
  67712. }
  67713. var textureSize = _this.getSize();
  67714. _this._canvas.width = textureSize.width;
  67715. _this._canvas.height = textureSize.height;
  67716. _this._context = _this._canvas.getContext("2d");
  67717. return _this;
  67718. }
  67719. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  67720. /**
  67721. * Gets the current state of canRescale
  67722. */
  67723. get: function () {
  67724. return true;
  67725. },
  67726. enumerable: true,
  67727. configurable: true
  67728. });
  67729. DynamicTexture.prototype._recreate = function (textureSize) {
  67730. this._canvas.width = textureSize.width;
  67731. this._canvas.height = textureSize.height;
  67732. this.releaseInternalTexture();
  67733. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  67734. };
  67735. /**
  67736. * Scales the texture
  67737. * @param ratio the scale factor to apply to both width and height
  67738. */
  67739. DynamicTexture.prototype.scale = function (ratio) {
  67740. var textureSize = this.getSize();
  67741. textureSize.width *= ratio;
  67742. textureSize.height *= ratio;
  67743. this._recreate(textureSize);
  67744. };
  67745. /**
  67746. * Resizes the texture
  67747. * @param width the new width
  67748. * @param height the new height
  67749. */
  67750. DynamicTexture.prototype.scaleTo = function (width, height) {
  67751. var textureSize = this.getSize();
  67752. textureSize.width = width;
  67753. textureSize.height = height;
  67754. this._recreate(textureSize);
  67755. };
  67756. /**
  67757. * Gets the context of the canvas used by the texture
  67758. * @returns the canvas context of the dynamic texture
  67759. */
  67760. DynamicTexture.prototype.getContext = function () {
  67761. return this._context;
  67762. };
  67763. /**
  67764. * Clears the texture
  67765. */
  67766. DynamicTexture.prototype.clear = function () {
  67767. var size = this.getSize();
  67768. this._context.fillRect(0, 0, size.width, size.height);
  67769. };
  67770. /**
  67771. * Updates the texture
  67772. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  67773. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  67774. */
  67775. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  67776. if (premulAlpha === void 0) { premulAlpha = false; }
  67777. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  67778. };
  67779. /**
  67780. * Draws text onto the texture
  67781. * @param text defines the text to be drawn
  67782. * @param x defines the placement of the text from the left
  67783. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  67784. * @param font defines the font to be used with font-style, font-size, font-name
  67785. * @param color defines the color used for the text
  67786. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  67787. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  67788. * @param update defines whether texture is immediately update (default is true)
  67789. */
  67790. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  67791. if (update === void 0) { update = true; }
  67792. var size = this.getSize();
  67793. if (clearColor) {
  67794. this._context.fillStyle = clearColor;
  67795. this._context.fillRect(0, 0, size.width, size.height);
  67796. }
  67797. this._context.font = font;
  67798. if (x === null || x === undefined) {
  67799. var textSize = this._context.measureText(text);
  67800. x = (size.width - textSize.width) / 2;
  67801. }
  67802. if (y === null || y === undefined) {
  67803. var fontSize = parseInt((font.replace(/\D/g, '')));
  67804. y = (size.height / 2) + (fontSize / 3.65);
  67805. }
  67806. this._context.fillStyle = color;
  67807. this._context.fillText(text, x, y);
  67808. if (update) {
  67809. this.update(invertY);
  67810. }
  67811. };
  67812. /**
  67813. * Clones the texture
  67814. * @returns the clone of the texture.
  67815. */
  67816. DynamicTexture.prototype.clone = function () {
  67817. var scene = this.getScene();
  67818. if (!scene) {
  67819. return this;
  67820. }
  67821. var textureSize = this.getSize();
  67822. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  67823. // Base texture
  67824. newTexture.hasAlpha = this.hasAlpha;
  67825. newTexture.level = this.level;
  67826. // Dynamic Texture
  67827. newTexture.wrapU = this.wrapU;
  67828. newTexture.wrapV = this.wrapV;
  67829. return newTexture;
  67830. };
  67831. /**
  67832. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  67833. * @returns a serialized dynamic texture object
  67834. */
  67835. DynamicTexture.prototype.serialize = function () {
  67836. var scene = this.getScene();
  67837. if (scene && !scene.isReady()) {
  67838. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  67839. }
  67840. var serializationObject = _super.prototype.serialize.call(this);
  67841. serializationObject.base64String = this._canvas.toDataURL();
  67842. serializationObject.invertY = this._invertY;
  67843. serializationObject.samplingMode = this.samplingMode;
  67844. return serializationObject;
  67845. };
  67846. /** @hidden */
  67847. DynamicTexture.prototype._rebuild = function () {
  67848. this.update();
  67849. };
  67850. return DynamicTexture;
  67851. }(BABYLON.Texture));
  67852. BABYLON.DynamicTexture = DynamicTexture;
  67853. })(BABYLON || (BABYLON = {}));
  67854. //# sourceMappingURL=babylon.dynamicTexture.js.map
  67855. var BABYLON;
  67856. (function (BABYLON) {
  67857. var VideoTexture = /** @class */ (function (_super) {
  67858. __extends(VideoTexture, _super);
  67859. /**
  67860. * Creates a video texture.
  67861. * Sample : https://doc.babylonjs.com/how_to/video_texture
  67862. * @param {string | null} name optional name, will detect from video source, if not defined
  67863. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  67864. * @param {BABYLON.Scene} scene is obviously the current scene.
  67865. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  67866. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  67867. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  67868. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  67869. */
  67870. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  67871. if (generateMipMaps === void 0) { generateMipMaps = false; }
  67872. if (invertY === void 0) { invertY = false; }
  67873. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67874. if (settings === void 0) { settings = {
  67875. autoPlay: true,
  67876. loop: true,
  67877. autoUpdateTexture: true,
  67878. }; }
  67879. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  67880. _this._onUserActionRequestedObservable = null;
  67881. _this._stillImageCaptured = false;
  67882. _this._poster = false;
  67883. _this._createInternalTexture = function () {
  67884. if (_this._texture != null) {
  67885. if (_this._poster) {
  67886. _this._texture.dispose();
  67887. _this._poster = false;
  67888. }
  67889. else {
  67890. return;
  67891. }
  67892. }
  67893. if (!_this._engine.needPOTTextures ||
  67894. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  67895. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67896. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67897. }
  67898. else {
  67899. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67900. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67901. _this._generateMipMaps = false;
  67902. }
  67903. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  67904. if (!_this.video.autoplay) {
  67905. var oldHandler_1 = _this.video.onplaying;
  67906. var error_1 = false;
  67907. _this.video.onplaying = function () {
  67908. _this.video.onplaying = oldHandler_1;
  67909. _this._texture.isReady = true;
  67910. _this._updateInternalTexture();
  67911. if (!error_1) {
  67912. _this.video.pause();
  67913. }
  67914. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  67915. _this.onLoadObservable.notifyObservers(_this);
  67916. }
  67917. };
  67918. var playing = _this.video.play();
  67919. if (playing) {
  67920. playing.then(function () {
  67921. // Everything is good.
  67922. })
  67923. .catch(function () {
  67924. error_1 = true;
  67925. // On Chrome for instance, new policies might prevent playing without user interaction.
  67926. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  67927. _this._onUserActionRequestedObservable.notifyObservers(_this);
  67928. }
  67929. });
  67930. }
  67931. else {
  67932. _this.video.onplaying = oldHandler_1;
  67933. _this._texture.isReady = true;
  67934. _this._updateInternalTexture();
  67935. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  67936. _this.onLoadObservable.notifyObservers(_this);
  67937. }
  67938. }
  67939. }
  67940. else {
  67941. _this._texture.isReady = true;
  67942. _this._updateInternalTexture();
  67943. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  67944. _this.onLoadObservable.notifyObservers(_this);
  67945. }
  67946. }
  67947. };
  67948. _this.reset = function () {
  67949. if (_this._texture == null) {
  67950. return;
  67951. }
  67952. if (!_this._poster) {
  67953. _this._texture.dispose();
  67954. _this._texture = null;
  67955. }
  67956. };
  67957. _this._updateInternalTexture = function (e) {
  67958. if (_this._texture == null || !_this._texture.isReady) {
  67959. return;
  67960. }
  67961. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  67962. return;
  67963. }
  67964. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  67965. };
  67966. _this._engine = _this.getScene().getEngine();
  67967. _this._generateMipMaps = generateMipMaps;
  67968. _this._samplingMode = samplingMode;
  67969. _this.autoUpdateTexture = settings.autoUpdateTexture;
  67970. _this.name = name || _this._getName(src);
  67971. _this.video = _this._getVideo(src);
  67972. if (settings.poster) {
  67973. _this.video.poster = settings.poster;
  67974. }
  67975. if (settings.autoPlay !== undefined) {
  67976. _this.video.autoplay = settings.autoPlay;
  67977. }
  67978. if (settings.loop !== undefined) {
  67979. _this.video.loop = settings.loop;
  67980. }
  67981. _this.video.setAttribute("playsinline", "");
  67982. _this.video.addEventListener("canplay", _this._createInternalTexture);
  67983. _this.video.addEventListener("paused", _this._updateInternalTexture);
  67984. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  67985. _this.video.addEventListener("emptied", _this.reset);
  67986. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  67987. _this._createInternalTexture();
  67988. }
  67989. if (settings.poster) {
  67990. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  67991. _this._poster = true;
  67992. }
  67993. return _this;
  67994. }
  67995. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  67996. get: function () {
  67997. if (!this._onUserActionRequestedObservable) {
  67998. this._onUserActionRequestedObservable = new BABYLON.Observable();
  67999. }
  68000. return this._onUserActionRequestedObservable;
  68001. },
  68002. enumerable: true,
  68003. configurable: true
  68004. });
  68005. VideoTexture.prototype._getName = function (src) {
  68006. if (src instanceof HTMLVideoElement) {
  68007. return src.currentSrc;
  68008. }
  68009. if (typeof src === "object") {
  68010. return src.toString();
  68011. }
  68012. return src;
  68013. };
  68014. ;
  68015. VideoTexture.prototype._getVideo = function (src) {
  68016. if (src instanceof HTMLVideoElement) {
  68017. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  68018. return src;
  68019. }
  68020. var video = document.createElement("video");
  68021. if (typeof src === "string") {
  68022. BABYLON.Tools.SetCorsBehavior(src, video);
  68023. video.src = src;
  68024. }
  68025. else {
  68026. BABYLON.Tools.SetCorsBehavior(src[0], video);
  68027. src.forEach(function (url) {
  68028. var source = document.createElement("source");
  68029. source.src = url;
  68030. video.appendChild(source);
  68031. });
  68032. }
  68033. return video;
  68034. };
  68035. ;
  68036. /**
  68037. * @hidden Internal method to initiate `update`.
  68038. */
  68039. VideoTexture.prototype._rebuild = function () {
  68040. this.update();
  68041. };
  68042. /**
  68043. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  68044. */
  68045. VideoTexture.prototype.update = function () {
  68046. if (!this.autoUpdateTexture) {
  68047. // Expecting user to call `updateTexture` manually
  68048. return;
  68049. }
  68050. this.updateTexture(true);
  68051. };
  68052. /**
  68053. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  68054. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  68055. */
  68056. VideoTexture.prototype.updateTexture = function (isVisible) {
  68057. if (!isVisible) {
  68058. return;
  68059. }
  68060. if (this.video.paused && this._stillImageCaptured) {
  68061. return;
  68062. }
  68063. this._stillImageCaptured = true;
  68064. this._updateInternalTexture();
  68065. };
  68066. /**
  68067. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  68068. * @param url New url.
  68069. */
  68070. VideoTexture.prototype.updateURL = function (url) {
  68071. this.video.src = url;
  68072. };
  68073. VideoTexture.prototype.dispose = function () {
  68074. _super.prototype.dispose.call(this);
  68075. if (this._onUserActionRequestedObservable) {
  68076. this._onUserActionRequestedObservable.clear();
  68077. this._onUserActionRequestedObservable = null;
  68078. }
  68079. this.video.removeEventListener("canplay", this._createInternalTexture);
  68080. this.video.removeEventListener("paused", this._updateInternalTexture);
  68081. this.video.removeEventListener("seeked", this._updateInternalTexture);
  68082. this.video.removeEventListener("emptied", this.reset);
  68083. this.video.pause();
  68084. };
  68085. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  68086. var video = document.createElement("video");
  68087. video.setAttribute('autoplay', '');
  68088. video.setAttribute('muted', '');
  68089. video.setAttribute('playsinline', '');
  68090. var constraintsDeviceId;
  68091. if (constraints && constraints.deviceId) {
  68092. constraintsDeviceId = {
  68093. exact: constraints.deviceId,
  68094. };
  68095. }
  68096. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  68097. if (navigator.mediaDevices) {
  68098. navigator.mediaDevices.getUserMedia({ video: constraints })
  68099. .then(function (stream) {
  68100. if (video.mozSrcObject !== undefined) {
  68101. // hack for Firefox < 19
  68102. video.mozSrcObject = stream;
  68103. }
  68104. else {
  68105. video.srcObject = stream;
  68106. }
  68107. var onPlaying = function () {
  68108. if (onReady) {
  68109. onReady(new VideoTexture("video", video, scene, true, true));
  68110. }
  68111. video.removeEventListener("playing", onPlaying);
  68112. };
  68113. video.addEventListener("playing", onPlaying);
  68114. video.play();
  68115. })
  68116. .catch(function (err) {
  68117. BABYLON.Tools.Error(err.name);
  68118. });
  68119. }
  68120. else {
  68121. navigator.getUserMedia =
  68122. navigator.getUserMedia ||
  68123. navigator.webkitGetUserMedia ||
  68124. navigator.mozGetUserMedia ||
  68125. navigator.msGetUserMedia;
  68126. if (navigator.getUserMedia) {
  68127. navigator.getUserMedia({
  68128. video: {
  68129. deviceId: constraintsDeviceId,
  68130. width: {
  68131. min: (constraints && constraints.minWidth) || 256,
  68132. max: (constraints && constraints.maxWidth) || 640,
  68133. },
  68134. height: {
  68135. min: (constraints && constraints.minHeight) || 256,
  68136. max: (constraints && constraints.maxHeight) || 480,
  68137. },
  68138. },
  68139. }, function (stream) {
  68140. if (video.mozSrcObject !== undefined) {
  68141. // hack for Firefox < 19
  68142. video.mozSrcObject = stream;
  68143. }
  68144. else {
  68145. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  68146. }
  68147. video.play();
  68148. if (onReady) {
  68149. onReady(new VideoTexture("video", video, scene, true, true));
  68150. }
  68151. }, function (e) {
  68152. BABYLON.Tools.Error(e.name);
  68153. });
  68154. }
  68155. }
  68156. };
  68157. return VideoTexture;
  68158. }(BABYLON.Texture));
  68159. BABYLON.VideoTexture = VideoTexture;
  68160. })(BABYLON || (BABYLON = {}));
  68161. //# sourceMappingURL=babylon.videoTexture.js.map
  68162. var BABYLON;
  68163. (function (BABYLON) {
  68164. var RawTexture = /** @class */ (function (_super) {
  68165. __extends(RawTexture, _super);
  68166. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  68167. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68168. if (invertY === void 0) { invertY = false; }
  68169. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68170. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68171. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68172. _this.format = format;
  68173. _this._engine = scene.getEngine();
  68174. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  68175. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68176. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68177. return _this;
  68178. }
  68179. RawTexture.prototype.update = function (data) {
  68180. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  68181. };
  68182. // Statics
  68183. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68184. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68185. if (invertY === void 0) { invertY = false; }
  68186. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68187. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  68188. };
  68189. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68190. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68191. if (invertY === void 0) { invertY = false; }
  68192. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68193. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  68194. };
  68195. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68196. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68197. if (invertY === void 0) { invertY = false; }
  68198. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68199. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  68200. };
  68201. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68202. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68203. if (invertY === void 0) { invertY = false; }
  68204. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68205. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68206. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  68207. };
  68208. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68209. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68210. if (invertY === void 0) { invertY = false; }
  68211. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68212. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68213. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  68214. };
  68215. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68216. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68217. if (invertY === void 0) { invertY = false; }
  68218. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68219. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  68220. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  68221. };
  68222. return RawTexture;
  68223. }(BABYLON.Texture));
  68224. BABYLON.RawTexture = RawTexture;
  68225. })(BABYLON || (BABYLON = {}));
  68226. //# sourceMappingURL=babylon.rawTexture.js.map
  68227. var BABYLON;
  68228. (function (BABYLON) {
  68229. /**
  68230. * Class used to store 3D textures containing user data
  68231. */
  68232. var RawTexture3D = /** @class */ (function (_super) {
  68233. __extends(RawTexture3D, _super);
  68234. /**
  68235. * Create a new RawTexture3D
  68236. * @param data defines the data of the texture
  68237. * @param width defines the width of the texture
  68238. * @param height defines the height of the texture
  68239. * @param depth defines the depth of the texture
  68240. * @param format defines the texture format to use
  68241. * @param scene defines the hosting scene
  68242. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  68243. * @param invertY defines if texture must be stored with Y axis inverted
  68244. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  68245. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  68246. */
  68247. function RawTexture3D(data, width, height, depth,
  68248. /** Gets or sets the texture format to use */
  68249. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  68250. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68251. if (invertY === void 0) { invertY = false; }
  68252. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68253. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68254. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68255. _this.format = format;
  68256. _this._engine = scene.getEngine();
  68257. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  68258. _this.is3D = true;
  68259. return _this;
  68260. }
  68261. /**
  68262. * Update the texture with new data
  68263. * @param data defines the data to store in the texture
  68264. */
  68265. RawTexture3D.prototype.update = function (data) {
  68266. if (!this._texture) {
  68267. return;
  68268. }
  68269. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  68270. };
  68271. return RawTexture3D;
  68272. }(BABYLON.Texture));
  68273. BABYLON.RawTexture3D = RawTexture3D;
  68274. })(BABYLON || (BABYLON = {}));
  68275. //# sourceMappingURL=babylon.rawTexture3D.js.map
  68276. var BABYLON;
  68277. (function (BABYLON) {
  68278. /**
  68279. * PostProcessManager is used to manage one or more post processes or post process pipelines
  68280. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  68281. */
  68282. var PostProcessManager = /** @class */ (function () {
  68283. /**
  68284. * Creates a new instance PostProcess
  68285. * @param scene The scene that the post process is associated with.
  68286. */
  68287. function PostProcessManager(scene) {
  68288. this._vertexBuffers = {};
  68289. this._scene = scene;
  68290. }
  68291. PostProcessManager.prototype._prepareBuffers = function () {
  68292. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  68293. return;
  68294. }
  68295. // VBO
  68296. var vertices = [];
  68297. vertices.push(1, 1);
  68298. vertices.push(-1, 1);
  68299. vertices.push(-1, -1);
  68300. vertices.push(1, -1);
  68301. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  68302. this._buildIndexBuffer();
  68303. };
  68304. PostProcessManager.prototype._buildIndexBuffer = function () {
  68305. // Indices
  68306. var indices = [];
  68307. indices.push(0);
  68308. indices.push(1);
  68309. indices.push(2);
  68310. indices.push(0);
  68311. indices.push(2);
  68312. indices.push(3);
  68313. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  68314. };
  68315. /**
  68316. * Rebuilds the vertex buffers of the manager.
  68317. * @hidden
  68318. */
  68319. PostProcessManager.prototype._rebuild = function () {
  68320. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68321. if (!vb) {
  68322. return;
  68323. }
  68324. vb._rebuild();
  68325. this._buildIndexBuffer();
  68326. };
  68327. // Methods
  68328. /**
  68329. * Prepares a frame to be run through a post process.
  68330. * @param sourceTexture The input texture to the post procesess. (default: null)
  68331. * @param postProcesses An array of post processes to be run. (default: null)
  68332. * @returns True if the post processes were able to be run.
  68333. * @hidden
  68334. */
  68335. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  68336. if (sourceTexture === void 0) { sourceTexture = null; }
  68337. if (postProcesses === void 0) { postProcesses = null; }
  68338. var camera = this._scene.activeCamera;
  68339. if (!camera) {
  68340. return false;
  68341. }
  68342. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  68343. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  68344. return false;
  68345. }
  68346. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  68347. return true;
  68348. };
  68349. /**
  68350. * Manually render a set of post processes to a texture.
  68351. * @param postProcesses An array of post processes to be run.
  68352. * @param targetTexture The target texture to render to.
  68353. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  68354. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  68355. * @param lodLevel defines which lod of the texture to render to
  68356. */
  68357. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  68358. if (targetTexture === void 0) { targetTexture = null; }
  68359. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  68360. if (faceIndex === void 0) { faceIndex = 0; }
  68361. if (lodLevel === void 0) { lodLevel = 0; }
  68362. var engine = this._scene.getEngine();
  68363. for (var index = 0; index < postProcesses.length; index++) {
  68364. if (index < postProcesses.length - 1) {
  68365. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  68366. }
  68367. else {
  68368. if (targetTexture) {
  68369. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  68370. }
  68371. else {
  68372. engine.restoreDefaultFramebuffer();
  68373. }
  68374. }
  68375. var pp = postProcesses[index];
  68376. var effect = pp.apply();
  68377. if (effect) {
  68378. pp.onBeforeRenderObservable.notifyObservers(effect);
  68379. // VBOs
  68380. this._prepareBuffers();
  68381. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  68382. // Draw order
  68383. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68384. pp.onAfterRenderObservable.notifyObservers(effect);
  68385. }
  68386. }
  68387. // Restore depth buffer
  68388. engine.setDepthBuffer(true);
  68389. engine.setDepthWrite(true);
  68390. };
  68391. /**
  68392. * Finalize the result of the output of the postprocesses.
  68393. * @param doNotPresent If true the result will not be displayed to the screen.
  68394. * @param targetTexture The target texture to render to.
  68395. * @param faceIndex The index of the face to bind the target texture to.
  68396. * @param postProcesses The array of post processes to render.
  68397. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  68398. * @hidden
  68399. */
  68400. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  68401. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  68402. var camera = this._scene.activeCamera;
  68403. if (!camera) {
  68404. return;
  68405. }
  68406. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  68407. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  68408. return;
  68409. }
  68410. var engine = this._scene.getEngine();
  68411. for (var index = 0, len = postProcesses.length; index < len; index++) {
  68412. var pp = postProcesses[index];
  68413. if (index < len - 1) {
  68414. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  68415. }
  68416. else {
  68417. if (targetTexture) {
  68418. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  68419. pp._outputTexture = targetTexture;
  68420. }
  68421. else {
  68422. engine.restoreDefaultFramebuffer();
  68423. pp._outputTexture = null;
  68424. }
  68425. }
  68426. if (doNotPresent) {
  68427. break;
  68428. }
  68429. var effect = pp.apply();
  68430. if (effect) {
  68431. pp.onBeforeRenderObservable.notifyObservers(effect);
  68432. // VBOs
  68433. this._prepareBuffers();
  68434. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  68435. // Draw order
  68436. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68437. pp.onAfterRenderObservable.notifyObservers(effect);
  68438. }
  68439. }
  68440. // Restore states
  68441. engine.setDepthBuffer(true);
  68442. engine.setDepthWrite(true);
  68443. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  68444. };
  68445. /**
  68446. * Disposes of the post process manager.
  68447. */
  68448. PostProcessManager.prototype.dispose = function () {
  68449. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68450. if (buffer) {
  68451. buffer.dispose();
  68452. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68453. }
  68454. if (this._indexBuffer) {
  68455. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  68456. this._indexBuffer = null;
  68457. }
  68458. };
  68459. return PostProcessManager;
  68460. }());
  68461. BABYLON.PostProcessManager = PostProcessManager;
  68462. })(BABYLON || (BABYLON = {}));
  68463. //# sourceMappingURL=babylon.postProcessManager.js.map
  68464. var BABYLON;
  68465. (function (BABYLON) {
  68466. /**
  68467. * PostProcess can be used to apply a shader to a texture after it has been rendered
  68468. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  68469. */
  68470. var PostProcess = /** @class */ (function () {
  68471. /**
  68472. * Creates a new instance PostProcess
  68473. * @param name The name of the PostProcess.
  68474. * @param fragmentUrl The url of the fragment shader to be used.
  68475. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  68476. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  68477. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68478. * @param camera The camera to apply the render pass to.
  68479. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68480. * @param engine The engine which the post process will be applied. (default: current engine)
  68481. * @param reusable If the post process can be reused on the same frame. (default: false)
  68482. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  68483. * @param textureType Type of textures used when performing the post process. (default: 0)
  68484. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  68485. * @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
  68486. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  68487. */
  68488. function PostProcess(
  68489. /** Name of the PostProcess. */
  68490. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  68491. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  68492. if (defines === void 0) { defines = null; }
  68493. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68494. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  68495. if (blockCompilation === void 0) { blockCompilation = false; }
  68496. this.name = name;
  68497. /**
  68498. * Width of the texture to apply the post process on
  68499. */
  68500. this.width = -1;
  68501. /**
  68502. * Height of the texture to apply the post process on
  68503. */
  68504. this.height = -1;
  68505. /**
  68506. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  68507. * @hidden
  68508. */
  68509. this._outputTexture = null;
  68510. /**
  68511. * If the buffer needs to be cleared before applying the post process. (default: true)
  68512. * Should be set to false if shader will overwrite all previous pixels.
  68513. */
  68514. this.autoClear = true;
  68515. /**
  68516. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  68517. */
  68518. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  68519. /**
  68520. * Animations to be used for the post processing
  68521. */
  68522. this.animations = new Array();
  68523. /**
  68524. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  68525. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  68526. */
  68527. this.enablePixelPerfectMode = false;
  68528. /**
  68529. * Force the postprocess to be applied without taking in account viewport
  68530. */
  68531. this.forceFullscreenViewport = true;
  68532. /**
  68533. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  68534. *
  68535. * | Value | Type | Description |
  68536. * | ----- | ----------------------------------- | ----------- |
  68537. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  68538. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  68539. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  68540. *
  68541. */
  68542. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  68543. /**
  68544. * Force textures to be a power of two (default: false)
  68545. */
  68546. this.alwaysForcePOT = false;
  68547. this._samples = 1;
  68548. /**
  68549. * Modify the scale of the post process to be the same as the viewport (default: false)
  68550. */
  68551. this.adaptScaleToCurrentViewport = false;
  68552. this._reusable = false;
  68553. /**
  68554. * Smart array of input and output textures for the post process.
  68555. * @hidden
  68556. */
  68557. this._textures = new BABYLON.SmartArray(2);
  68558. /**
  68559. * The index in _textures that corresponds to the output texture.
  68560. * @hidden
  68561. */
  68562. this._currentRenderTextureInd = 0;
  68563. this._scaleRatio = new BABYLON.Vector2(1, 1);
  68564. this._texelSize = BABYLON.Vector2.Zero();
  68565. // Events
  68566. /**
  68567. * An event triggered when the postprocess is activated.
  68568. */
  68569. this.onActivateObservable = new BABYLON.Observable();
  68570. /**
  68571. * An event triggered when the postprocess changes its size.
  68572. */
  68573. this.onSizeChangedObservable = new BABYLON.Observable();
  68574. /**
  68575. * An event triggered when the postprocess applies its effect.
  68576. */
  68577. this.onApplyObservable = new BABYLON.Observable();
  68578. /**
  68579. * An event triggered before rendering the postprocess
  68580. */
  68581. this.onBeforeRenderObservable = new BABYLON.Observable();
  68582. /**
  68583. * An event triggered after rendering the postprocess
  68584. */
  68585. this.onAfterRenderObservable = new BABYLON.Observable();
  68586. if (camera != null) {
  68587. this._camera = camera;
  68588. this._scene = camera.getScene();
  68589. camera.attachPostProcess(this);
  68590. this._engine = this._scene.getEngine();
  68591. this._scene.postProcesses.push(this);
  68592. }
  68593. else if (engine) {
  68594. this._engine = engine;
  68595. this._engine.postProcesses.push(this);
  68596. }
  68597. this._options = options;
  68598. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  68599. this._reusable = reusable || false;
  68600. this._textureType = textureType;
  68601. this._samplers = samplers || [];
  68602. this._samplers.push("textureSampler");
  68603. this._fragmentUrl = fragmentUrl;
  68604. this._vertexUrl = vertexUrl;
  68605. this._parameters = parameters || [];
  68606. this._parameters.push("scale");
  68607. this._indexParameters = indexParameters;
  68608. if (!blockCompilation) {
  68609. this.updateEffect(defines);
  68610. }
  68611. }
  68612. Object.defineProperty(PostProcess.prototype, "samples", {
  68613. /**
  68614. * Number of sample textures (default: 1)
  68615. */
  68616. get: function () {
  68617. return this._samples;
  68618. },
  68619. set: function (n) {
  68620. var _this = this;
  68621. this._samples = n;
  68622. this._textures.forEach(function (texture) {
  68623. if (texture.samples !== _this._samples) {
  68624. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  68625. }
  68626. });
  68627. },
  68628. enumerable: true,
  68629. configurable: true
  68630. });
  68631. Object.defineProperty(PostProcess.prototype, "onActivate", {
  68632. /**
  68633. * A function that is added to the onActivateObservable
  68634. */
  68635. set: function (callback) {
  68636. if (this._onActivateObserver) {
  68637. this.onActivateObservable.remove(this._onActivateObserver);
  68638. }
  68639. if (callback) {
  68640. this._onActivateObserver = this.onActivateObservable.add(callback);
  68641. }
  68642. },
  68643. enumerable: true,
  68644. configurable: true
  68645. });
  68646. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  68647. /**
  68648. * A function that is added to the onSizeChangedObservable
  68649. */
  68650. set: function (callback) {
  68651. if (this._onSizeChangedObserver) {
  68652. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  68653. }
  68654. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  68655. },
  68656. enumerable: true,
  68657. configurable: true
  68658. });
  68659. Object.defineProperty(PostProcess.prototype, "onApply", {
  68660. /**
  68661. * A function that is added to the onApplyObservable
  68662. */
  68663. set: function (callback) {
  68664. if (this._onApplyObserver) {
  68665. this.onApplyObservable.remove(this._onApplyObserver);
  68666. }
  68667. this._onApplyObserver = this.onApplyObservable.add(callback);
  68668. },
  68669. enumerable: true,
  68670. configurable: true
  68671. });
  68672. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  68673. /**
  68674. * A function that is added to the onBeforeRenderObservable
  68675. */
  68676. set: function (callback) {
  68677. if (this._onBeforeRenderObserver) {
  68678. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  68679. }
  68680. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  68681. },
  68682. enumerable: true,
  68683. configurable: true
  68684. });
  68685. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  68686. /**
  68687. * A function that is added to the onAfterRenderObservable
  68688. */
  68689. set: function (callback) {
  68690. if (this._onAfterRenderObserver) {
  68691. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  68692. }
  68693. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  68694. },
  68695. enumerable: true,
  68696. configurable: true
  68697. });
  68698. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  68699. /**
  68700. * 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
  68701. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  68702. */
  68703. get: function () {
  68704. return this._textures.data[this._currentRenderTextureInd];
  68705. },
  68706. set: function (value) {
  68707. this._forcedOutputTexture = value;
  68708. },
  68709. enumerable: true,
  68710. configurable: true
  68711. });
  68712. /**
  68713. * Gets the camera which post process is applied to.
  68714. * @returns The camera the post process is applied to.
  68715. */
  68716. PostProcess.prototype.getCamera = function () {
  68717. return this._camera;
  68718. };
  68719. Object.defineProperty(PostProcess.prototype, "texelSize", {
  68720. /**
  68721. * Gets the texel size of the postprocess.
  68722. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  68723. */
  68724. get: function () {
  68725. if (this._shareOutputWithPostProcess) {
  68726. return this._shareOutputWithPostProcess.texelSize;
  68727. }
  68728. if (this._forcedOutputTexture) {
  68729. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  68730. }
  68731. return this._texelSize;
  68732. },
  68733. enumerable: true,
  68734. configurable: true
  68735. });
  68736. /**
  68737. * Gets the engine which this post process belongs to.
  68738. * @returns The engine the post process was enabled with.
  68739. */
  68740. PostProcess.prototype.getEngine = function () {
  68741. return this._engine;
  68742. };
  68743. /**
  68744. * The effect that is created when initializing the post process.
  68745. * @returns The created effect corrisponding the the postprocess.
  68746. */
  68747. PostProcess.prototype.getEffect = function () {
  68748. return this._effect;
  68749. };
  68750. /**
  68751. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  68752. * @param postProcess The post process to share the output with.
  68753. * @returns This post process.
  68754. */
  68755. PostProcess.prototype.shareOutputWith = function (postProcess) {
  68756. this._disposeTextures();
  68757. this._shareOutputWithPostProcess = postProcess;
  68758. return this;
  68759. };
  68760. /**
  68761. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  68762. * This should be called if the post process that shares output with this post process is disabled/disposed.
  68763. */
  68764. PostProcess.prototype.useOwnOutput = function () {
  68765. if (this._textures.length == 0) {
  68766. this._textures = new BABYLON.SmartArray(2);
  68767. }
  68768. this._shareOutputWithPostProcess = null;
  68769. };
  68770. /**
  68771. * Updates the effect with the current post process compile time values and recompiles the shader.
  68772. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  68773. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  68774. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  68775. * @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
  68776. * @param onCompiled Called when the shader has been compiled.
  68777. * @param onError Called if there is an error when compiling a shader.
  68778. */
  68779. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  68780. if (defines === void 0) { defines = null; }
  68781. if (uniforms === void 0) { uniforms = null; }
  68782. if (samplers === void 0) { samplers = null; }
  68783. 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);
  68784. };
  68785. /**
  68786. * The post process is reusable if it can be used multiple times within one frame.
  68787. * @returns If the post process is reusable
  68788. */
  68789. PostProcess.prototype.isReusable = function () {
  68790. return this._reusable;
  68791. };
  68792. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  68793. PostProcess.prototype.markTextureDirty = function () {
  68794. this.width = -1;
  68795. };
  68796. /**
  68797. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  68798. * 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.
  68799. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  68800. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  68801. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  68802. * @returns The target texture that was bound to be written to.
  68803. */
  68804. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  68805. var _this = this;
  68806. if (sourceTexture === void 0) { sourceTexture = null; }
  68807. camera = camera || this._camera;
  68808. var scene = camera.getScene();
  68809. var engine = scene.getEngine();
  68810. var maxSize = engine.getCaps().maxTextureSize;
  68811. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  68812. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  68813. // 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
  68814. var webVRCamera = camera.parent;
  68815. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  68816. requiredWidth /= 2;
  68817. }
  68818. var desiredWidth = (this._options.width || requiredWidth);
  68819. var desiredHeight = this._options.height || requiredHeight;
  68820. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  68821. if (this.adaptScaleToCurrentViewport) {
  68822. var currentViewport = engine.currentViewport;
  68823. if (currentViewport) {
  68824. desiredWidth *= currentViewport.width;
  68825. desiredHeight *= currentViewport.height;
  68826. }
  68827. }
  68828. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  68829. if (!this._options.width) {
  68830. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  68831. }
  68832. if (!this._options.height) {
  68833. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  68834. }
  68835. }
  68836. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  68837. if (this._textures.length > 0) {
  68838. for (var i = 0; i < this._textures.length; i++) {
  68839. this._engine._releaseTexture(this._textures.data[i]);
  68840. }
  68841. this._textures.reset();
  68842. }
  68843. this.width = desiredWidth;
  68844. this.height = desiredHeight;
  68845. var textureSize = { width: this.width, height: this.height };
  68846. var textureOptions = {
  68847. generateMipMaps: false,
  68848. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  68849. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  68850. samplingMode: this.renderTargetSamplingMode,
  68851. type: this._textureType
  68852. };
  68853. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  68854. if (this._reusable) {
  68855. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  68856. }
  68857. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  68858. this.onSizeChangedObservable.notifyObservers(this);
  68859. }
  68860. this._textures.forEach(function (texture) {
  68861. if (texture.samples !== _this.samples) {
  68862. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  68863. }
  68864. });
  68865. }
  68866. var target;
  68867. if (this._shareOutputWithPostProcess) {
  68868. target = this._shareOutputWithPostProcess.inputTexture;
  68869. }
  68870. else if (this._forcedOutputTexture) {
  68871. target = this._forcedOutputTexture;
  68872. this.width = this._forcedOutputTexture.width;
  68873. this.height = this._forcedOutputTexture.height;
  68874. }
  68875. else {
  68876. target = this.inputTexture;
  68877. }
  68878. // Bind the input of this post process to be used as the output of the previous post process.
  68879. if (this.enablePixelPerfectMode) {
  68880. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  68881. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  68882. }
  68883. else {
  68884. this._scaleRatio.copyFromFloats(1, 1);
  68885. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  68886. }
  68887. this.onActivateObservable.notifyObservers(camera);
  68888. // Clear
  68889. if (scene._allowPostProcessClear && this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  68890. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  68891. }
  68892. if (this._reusable) {
  68893. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  68894. }
  68895. return target;
  68896. };
  68897. Object.defineProperty(PostProcess.prototype, "isSupported", {
  68898. /**
  68899. * If the post process is supported.
  68900. */
  68901. get: function () {
  68902. return this._effect.isSupported;
  68903. },
  68904. enumerable: true,
  68905. configurable: true
  68906. });
  68907. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  68908. /**
  68909. * The aspect ratio of the output texture.
  68910. */
  68911. get: function () {
  68912. if (this._shareOutputWithPostProcess) {
  68913. return this._shareOutputWithPostProcess.aspectRatio;
  68914. }
  68915. if (this._forcedOutputTexture) {
  68916. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  68917. }
  68918. return this.width / this.height;
  68919. },
  68920. enumerable: true,
  68921. configurable: true
  68922. });
  68923. /**
  68924. * Get a value indicating if the post-process is ready to be used
  68925. * @returns true if the post-process is ready (shader is compiled)
  68926. */
  68927. PostProcess.prototype.isReady = function () {
  68928. return this._effect && this._effect.isReady();
  68929. };
  68930. /**
  68931. * Binds all textures and uniforms to the shader, this will be run on every pass.
  68932. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  68933. */
  68934. PostProcess.prototype.apply = function () {
  68935. // Check
  68936. if (!this._effect || !this._effect.isReady())
  68937. return null;
  68938. // States
  68939. this._engine.enableEffect(this._effect);
  68940. this._engine.setState(false);
  68941. this._engine.setDepthBuffer(false);
  68942. this._engine.setDepthWrite(false);
  68943. // Alpha
  68944. this._engine.setAlphaMode(this.alphaMode);
  68945. if (this.alphaConstants) {
  68946. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  68947. }
  68948. // Bind the output texture of the preivous post process as the input to this post process.
  68949. var source;
  68950. if (this._shareOutputWithPostProcess) {
  68951. source = this._shareOutputWithPostProcess.inputTexture;
  68952. }
  68953. else if (this._forcedOutputTexture) {
  68954. source = this._forcedOutputTexture;
  68955. }
  68956. else {
  68957. source = this.inputTexture;
  68958. }
  68959. this._effect._bindTexture("textureSampler", source);
  68960. // Parameters
  68961. this._effect.setVector2("scale", this._scaleRatio);
  68962. this.onApplyObservable.notifyObservers(this._effect);
  68963. return this._effect;
  68964. };
  68965. PostProcess.prototype._disposeTextures = function () {
  68966. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  68967. return;
  68968. }
  68969. if (this._textures.length > 0) {
  68970. for (var i = 0; i < this._textures.length; i++) {
  68971. this._engine._releaseTexture(this._textures.data[i]);
  68972. }
  68973. }
  68974. this._textures.dispose();
  68975. };
  68976. /**
  68977. * Disposes the post process.
  68978. * @param camera The camera to dispose the post process on.
  68979. */
  68980. PostProcess.prototype.dispose = function (camera) {
  68981. camera = camera || this._camera;
  68982. this._disposeTextures();
  68983. if (this._scene) {
  68984. var index_1 = this._scene.postProcesses.indexOf(this);
  68985. if (index_1 !== -1) {
  68986. this._scene.postProcesses.splice(index_1, 1);
  68987. }
  68988. }
  68989. else {
  68990. var index_2 = this._engine.postProcesses.indexOf(this);
  68991. if (index_2 !== -1) {
  68992. this._engine.postProcesses.splice(index_2, 1);
  68993. }
  68994. }
  68995. if (!camera) {
  68996. return;
  68997. }
  68998. camera.detachPostProcess(this);
  68999. var index = camera._postProcesses.indexOf(this);
  69000. if (index === 0 && camera._postProcesses.length > 0) {
  69001. var firstPostProcess = this._camera._getFirstPostProcess();
  69002. if (firstPostProcess) {
  69003. firstPostProcess.markTextureDirty();
  69004. }
  69005. }
  69006. this.onActivateObservable.clear();
  69007. this.onAfterRenderObservable.clear();
  69008. this.onApplyObservable.clear();
  69009. this.onBeforeRenderObservable.clear();
  69010. this.onSizeChangedObservable.clear();
  69011. };
  69012. return PostProcess;
  69013. }());
  69014. BABYLON.PostProcess = PostProcess;
  69015. })(BABYLON || (BABYLON = {}));
  69016. //# sourceMappingURL=babylon.postProcess.js.map
  69017. var BABYLON;
  69018. (function (BABYLON) {
  69019. var PassPostProcess = /** @class */ (function (_super) {
  69020. __extends(PassPostProcess, _super);
  69021. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69022. if (camera === void 0) { camera = null; }
  69023. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69024. if (blockCompilation === void 0) { blockCompilation = false; }
  69025. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  69026. }
  69027. return PassPostProcess;
  69028. }(BABYLON.PostProcess));
  69029. BABYLON.PassPostProcess = PassPostProcess;
  69030. })(BABYLON || (BABYLON = {}));
  69031. //# sourceMappingURL=babylon.passPostProcess.js.map
  69032. var __assign = (this && this.__assign) || function () {
  69033. __assign = Object.assign || function(t) {
  69034. for (var s, i = 1, n = arguments.length; i < n; i++) {
  69035. s = arguments[i];
  69036. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  69037. t[p] = s[p];
  69038. }
  69039. return t;
  69040. };
  69041. return __assign.apply(this, arguments);
  69042. };
  69043. var BABYLON;
  69044. (function (BABYLON) {
  69045. /**
  69046. * Default implementation IShadowGenerator.
  69047. * This is the main object responsible of generating shadows in the framework.
  69048. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  69049. */
  69050. var ShadowGenerator = /** @class */ (function () {
  69051. /**
  69052. * Creates a ShadowGenerator object.
  69053. * A ShadowGenerator is the required tool to use the shadows.
  69054. * Each light casting shadows needs to use its own ShadowGenerator.
  69055. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  69056. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  69057. * @param light The light object generating the shadows.
  69058. * @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.
  69059. */
  69060. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  69061. this._bias = 0.00005;
  69062. this._normalBias = 0;
  69063. this._blurBoxOffset = 1;
  69064. this._blurScale = 2;
  69065. this._blurKernel = 1;
  69066. this._useKernelBlur = false;
  69067. this._filter = ShadowGenerator.FILTER_NONE;
  69068. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  69069. this._contactHardeningLightSizeUVRatio = 0.1;
  69070. this._darkness = 0;
  69071. this._transparencyShadow = false;
  69072. /**
  69073. * Controls the extent to which the shadows fade out at the edge of the frustum
  69074. * Used only by directionals and spots
  69075. */
  69076. this.frustumEdgeFalloff = 0;
  69077. /**
  69078. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  69079. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  69080. * It might on the other hand introduce peter panning.
  69081. */
  69082. this.forceBackFacesOnly = false;
  69083. this._lightDirection = BABYLON.Vector3.Zero();
  69084. this._viewMatrix = BABYLON.Matrix.Zero();
  69085. this._projectionMatrix = BABYLON.Matrix.Zero();
  69086. this._transformMatrix = BABYLON.Matrix.Zero();
  69087. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  69088. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  69089. this._currentFaceIndex = 0;
  69090. this._currentFaceIndexCache = 0;
  69091. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  69092. this._mapSize = mapSize;
  69093. this._light = light;
  69094. this._scene = light.getScene();
  69095. light._shadowGenerator = this;
  69096. // Texture type fallback from float to int if not supported.
  69097. var caps = this._scene.getEngine().getCaps();
  69098. if (!useFullFloatFirst) {
  69099. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  69100. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69101. }
  69102. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  69103. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69104. }
  69105. else {
  69106. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69107. }
  69108. }
  69109. else {
  69110. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  69111. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69112. }
  69113. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  69114. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69115. }
  69116. else {
  69117. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69118. }
  69119. }
  69120. this._initializeGenerator();
  69121. this._applyFilterValues();
  69122. }
  69123. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  69124. /**
  69125. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  69126. */
  69127. get: function () {
  69128. return this._bias;
  69129. },
  69130. /**
  69131. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  69132. */
  69133. set: function (bias) {
  69134. this._bias = bias;
  69135. },
  69136. enumerable: true,
  69137. configurable: true
  69138. });
  69139. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  69140. /**
  69141. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  69142. */
  69143. get: function () {
  69144. return this._normalBias;
  69145. },
  69146. /**
  69147. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  69148. */
  69149. set: function (normalBias) {
  69150. this._normalBias = normalBias;
  69151. },
  69152. enumerable: true,
  69153. configurable: true
  69154. });
  69155. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  69156. /**
  69157. * Gets the blur box offset: offset applied during the blur pass.
  69158. * Only usefull if useKernelBlur = false
  69159. */
  69160. get: function () {
  69161. return this._blurBoxOffset;
  69162. },
  69163. /**
  69164. * Sets the blur box offset: offset applied during the blur pass.
  69165. * Only usefull if useKernelBlur = false
  69166. */
  69167. set: function (value) {
  69168. if (this._blurBoxOffset === value) {
  69169. return;
  69170. }
  69171. this._blurBoxOffset = value;
  69172. this._disposeBlurPostProcesses();
  69173. },
  69174. enumerable: true,
  69175. configurable: true
  69176. });
  69177. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  69178. /**
  69179. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  69180. * 2 means half of the size.
  69181. */
  69182. get: function () {
  69183. return this._blurScale;
  69184. },
  69185. /**
  69186. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  69187. * 2 means half of the size.
  69188. */
  69189. set: function (value) {
  69190. if (this._blurScale === value) {
  69191. return;
  69192. }
  69193. this._blurScale = value;
  69194. this._disposeBlurPostProcesses();
  69195. },
  69196. enumerable: true,
  69197. configurable: true
  69198. });
  69199. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  69200. /**
  69201. * Gets the blur kernel: kernel size of the blur pass.
  69202. * Only usefull if useKernelBlur = true
  69203. */
  69204. get: function () {
  69205. return this._blurKernel;
  69206. },
  69207. /**
  69208. * Sets the blur kernel: kernel size of the blur pass.
  69209. * Only usefull if useKernelBlur = true
  69210. */
  69211. set: function (value) {
  69212. if (this._blurKernel === value) {
  69213. return;
  69214. }
  69215. this._blurKernel = value;
  69216. this._disposeBlurPostProcesses();
  69217. },
  69218. enumerable: true,
  69219. configurable: true
  69220. });
  69221. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  69222. /**
  69223. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  69224. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  69225. */
  69226. get: function () {
  69227. return this._useKernelBlur;
  69228. },
  69229. /**
  69230. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  69231. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  69232. */
  69233. set: function (value) {
  69234. if (this._useKernelBlur === value) {
  69235. return;
  69236. }
  69237. this._useKernelBlur = value;
  69238. this._disposeBlurPostProcesses();
  69239. },
  69240. enumerable: true,
  69241. configurable: true
  69242. });
  69243. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  69244. /**
  69245. * Gets the depth scale used in ESM mode.
  69246. */
  69247. get: function () {
  69248. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  69249. },
  69250. /**
  69251. * Sets the depth scale used in ESM mode.
  69252. * This can override the scale stored on the light.
  69253. */
  69254. set: function (value) {
  69255. this._depthScale = value;
  69256. },
  69257. enumerable: true,
  69258. configurable: true
  69259. });
  69260. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  69261. /**
  69262. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  69263. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  69264. */
  69265. get: function () {
  69266. return this._filter;
  69267. },
  69268. /**
  69269. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  69270. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  69271. */
  69272. set: function (value) {
  69273. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  69274. if (this._light.needCube()) {
  69275. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  69276. this.useExponentialShadowMap = true;
  69277. return;
  69278. }
  69279. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  69280. this.useCloseExponentialShadowMap = true;
  69281. return;
  69282. }
  69283. // PCF on cubemap would also be expensive
  69284. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  69285. this.usePoissonSampling = true;
  69286. return;
  69287. }
  69288. }
  69289. // Weblg1 fallback for PCF.
  69290. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  69291. if (this._scene.getEngine().webGLVersion === 1) {
  69292. this.usePoissonSampling = true;
  69293. return;
  69294. }
  69295. }
  69296. if (this._filter === value) {
  69297. return;
  69298. }
  69299. this._filter = value;
  69300. this._disposeBlurPostProcesses();
  69301. this._applyFilterValues();
  69302. this._light._markMeshesAsLightDirty();
  69303. },
  69304. enumerable: true,
  69305. configurable: true
  69306. });
  69307. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  69308. /**
  69309. * Gets if the current filter is set to Poisson Sampling.
  69310. */
  69311. get: function () {
  69312. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  69313. },
  69314. /**
  69315. * Sets the current filter to Poisson Sampling.
  69316. */
  69317. set: function (value) {
  69318. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  69319. return;
  69320. }
  69321. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  69322. },
  69323. enumerable: true,
  69324. configurable: true
  69325. });
  69326. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  69327. /**
  69328. * Gets if the current filter is set to VSM.
  69329. * DEPRECATED. Should use useExponentialShadowMap instead.
  69330. */
  69331. get: function () {
  69332. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  69333. return this.useExponentialShadowMap;
  69334. },
  69335. /**
  69336. * Sets the current filter is to VSM.
  69337. * DEPRECATED. Should use useExponentialShadowMap instead.
  69338. */
  69339. set: function (value) {
  69340. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  69341. this.useExponentialShadowMap = value;
  69342. },
  69343. enumerable: true,
  69344. configurable: true
  69345. });
  69346. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  69347. /**
  69348. * Gets if the current filter is set to blurred VSM.
  69349. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  69350. */
  69351. get: function () {
  69352. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  69353. return this.useBlurExponentialShadowMap;
  69354. },
  69355. /**
  69356. * Sets the current filter is to blurred VSM.
  69357. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  69358. */
  69359. set: function (value) {
  69360. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  69361. this.useBlurExponentialShadowMap = value;
  69362. },
  69363. enumerable: true,
  69364. configurable: true
  69365. });
  69366. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  69367. /**
  69368. * Gets if the current filter is set to ESM.
  69369. */
  69370. get: function () {
  69371. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  69372. },
  69373. /**
  69374. * Sets the current filter is to ESM.
  69375. */
  69376. set: function (value) {
  69377. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  69378. return;
  69379. }
  69380. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69381. },
  69382. enumerable: true,
  69383. configurable: true
  69384. });
  69385. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  69386. /**
  69387. * Gets if the current filter is set to filtered ESM.
  69388. */
  69389. get: function () {
  69390. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  69391. },
  69392. /**
  69393. * Gets if the current filter is set to filtered ESM.
  69394. */
  69395. set: function (value) {
  69396. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  69397. return;
  69398. }
  69399. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69400. },
  69401. enumerable: true,
  69402. configurable: true
  69403. });
  69404. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  69405. /**
  69406. * Gets if the current filter is set to "close ESM" (using the inverse of the
  69407. * exponential to prevent steep falloff artifacts).
  69408. */
  69409. get: function () {
  69410. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  69411. },
  69412. /**
  69413. * Sets the current filter to "close ESM" (using the inverse of the
  69414. * exponential to prevent steep falloff artifacts).
  69415. */
  69416. set: function (value) {
  69417. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  69418. return;
  69419. }
  69420. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69421. },
  69422. enumerable: true,
  69423. configurable: true
  69424. });
  69425. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  69426. /**
  69427. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  69428. * exponential to prevent steep falloff artifacts).
  69429. */
  69430. get: function () {
  69431. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  69432. },
  69433. /**
  69434. * Sets the current filter to filtered "close ESM" (using the inverse of the
  69435. * exponential to prevent steep falloff artifacts).
  69436. */
  69437. set: function (value) {
  69438. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  69439. return;
  69440. }
  69441. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69442. },
  69443. enumerable: true,
  69444. configurable: true
  69445. });
  69446. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  69447. /**
  69448. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  69449. */
  69450. get: function () {
  69451. return this.filter === ShadowGenerator.FILTER_PCF;
  69452. },
  69453. /**
  69454. * Sets the current filter to "PCF" (percentage closer filtering).
  69455. */
  69456. set: function (value) {
  69457. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  69458. return;
  69459. }
  69460. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  69461. },
  69462. enumerable: true,
  69463. configurable: true
  69464. });
  69465. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  69466. /**
  69467. * Gets the PCF or PCSS Quality.
  69468. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  69469. */
  69470. get: function () {
  69471. return this._filteringQuality;
  69472. },
  69473. /**
  69474. * Sets the PCF or PCSS Quality.
  69475. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  69476. */
  69477. set: function (filteringQuality) {
  69478. this._filteringQuality = filteringQuality;
  69479. },
  69480. enumerable: true,
  69481. configurable: true
  69482. });
  69483. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  69484. /**
  69485. * Gets if the current filter is set to "PCSS" (contact hardening).
  69486. */
  69487. get: function () {
  69488. return this.filter === ShadowGenerator.FILTER_PCSS;
  69489. },
  69490. /**
  69491. * Sets the current filter to "PCSS" (contact hardening).
  69492. */
  69493. set: function (value) {
  69494. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  69495. return;
  69496. }
  69497. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  69498. },
  69499. enumerable: true,
  69500. configurable: true
  69501. });
  69502. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  69503. /**
  69504. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  69505. * Using a ratio helps keeping shape stability independently of the map size.
  69506. *
  69507. * It does not account for the light projection as it was having too much
  69508. * instability during the light setup or during light position changes.
  69509. *
  69510. * Only valid if useContactHardeningShadow is true.
  69511. */
  69512. get: function () {
  69513. return this._contactHardeningLightSizeUVRatio;
  69514. },
  69515. /**
  69516. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  69517. * Using a ratio helps keeping shape stability independently of the map size.
  69518. *
  69519. * It does not account for the light projection as it was having too much
  69520. * instability during the light setup or during light position changes.
  69521. *
  69522. * Only valid if useContactHardeningShadow is true.
  69523. */
  69524. set: function (contactHardeningLightSizeUVRatio) {
  69525. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  69526. },
  69527. enumerable: true,
  69528. configurable: true
  69529. });
  69530. /**
  69531. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  69532. * 0 means strongest and 1 would means no shadow.
  69533. * @returns the darkness.
  69534. */
  69535. ShadowGenerator.prototype.getDarkness = function () {
  69536. return this._darkness;
  69537. };
  69538. /**
  69539. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  69540. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  69541. * @returns the shadow generator allowing fluent coding.
  69542. */
  69543. ShadowGenerator.prototype.setDarkness = function (darkness) {
  69544. if (darkness >= 1.0)
  69545. this._darkness = 1.0;
  69546. else if (darkness <= 0.0)
  69547. this._darkness = 0.0;
  69548. else
  69549. this._darkness = darkness;
  69550. return this;
  69551. };
  69552. /**
  69553. * Sets the ability to have transparent shadow (boolean).
  69554. * @param transparent True if transparent else False
  69555. * @returns the shadow generator allowing fluent coding
  69556. */
  69557. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  69558. this._transparencyShadow = transparent;
  69559. return this;
  69560. };
  69561. /**
  69562. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  69563. * @returns The render target texture if present otherwise, null
  69564. */
  69565. ShadowGenerator.prototype.getShadowMap = function () {
  69566. return this._shadowMap;
  69567. };
  69568. /**
  69569. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  69570. * @returns The render target texture if the shadow map is present otherwise, null
  69571. */
  69572. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  69573. if (this._shadowMap2) {
  69574. return this._shadowMap2;
  69575. }
  69576. return this._shadowMap;
  69577. };
  69578. /**
  69579. * Helper function to add a mesh and its descendants to the list of shadow casters.
  69580. * @param mesh Mesh to add
  69581. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  69582. * @returns the Shadow Generator itself
  69583. */
  69584. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  69585. if (includeDescendants === void 0) { includeDescendants = true; }
  69586. var _a;
  69587. if (!this._shadowMap) {
  69588. return this;
  69589. }
  69590. if (!this._shadowMap.renderList) {
  69591. this._shadowMap.renderList = [];
  69592. }
  69593. this._shadowMap.renderList.push(mesh);
  69594. if (includeDescendants) {
  69595. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  69596. }
  69597. return this;
  69598. };
  69599. /**
  69600. * Helper function to remove a mesh and its descendants from the list of shadow casters
  69601. * @param mesh Mesh to remove
  69602. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  69603. * @returns the Shadow Generator itself
  69604. */
  69605. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  69606. if (includeDescendants === void 0) { includeDescendants = true; }
  69607. if (!this._shadowMap || !this._shadowMap.renderList) {
  69608. return this;
  69609. }
  69610. var index = this._shadowMap.renderList.indexOf(mesh);
  69611. if (index !== -1) {
  69612. this._shadowMap.renderList.splice(index, 1);
  69613. }
  69614. if (includeDescendants) {
  69615. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  69616. var child = _a[_i];
  69617. this.removeShadowCaster(child);
  69618. }
  69619. }
  69620. return this;
  69621. };
  69622. /**
  69623. * Returns the associated light object.
  69624. * @returns the light generating the shadow
  69625. */
  69626. ShadowGenerator.prototype.getLight = function () {
  69627. return this._light;
  69628. };
  69629. ShadowGenerator.prototype._initializeGenerator = function () {
  69630. this._light._markMeshesAsLightDirty();
  69631. this._initializeShadowMap();
  69632. };
  69633. ShadowGenerator.prototype._initializeShadowMap = function () {
  69634. var _this = this;
  69635. // Render target
  69636. var engine = this._scene.getEngine();
  69637. if (engine.webGLVersion > 1) {
  69638. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  69639. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  69640. }
  69641. else {
  69642. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  69643. }
  69644. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69645. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69646. this._shadowMap.anisotropicFilteringLevel = 1;
  69647. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69648. this._shadowMap.renderParticles = false;
  69649. this._shadowMap.ignoreCameraViewport = true;
  69650. // Record Face Index before render.
  69651. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  69652. _this._currentFaceIndex = faceIndex;
  69653. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69654. engine.setColorWrite(false);
  69655. }
  69656. });
  69657. // Custom render function.
  69658. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  69659. // Blur if required afer render.
  69660. this._shadowMap.onAfterUnbindObservable.add(function () {
  69661. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69662. engine.setColorWrite(true);
  69663. }
  69664. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  69665. return;
  69666. }
  69667. var shadowMap = _this.getShadowMapForRendering();
  69668. if (shadowMap) {
  69669. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  69670. }
  69671. });
  69672. // Clear according to the chosen filter.
  69673. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  69674. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  69675. this._shadowMap.onClearObservable.add(function (engine) {
  69676. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69677. engine.clear(clearOne, false, true, false);
  69678. }
  69679. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  69680. engine.clear(clearZero, true, true, false);
  69681. }
  69682. else {
  69683. engine.clear(clearOne, true, true, false);
  69684. }
  69685. });
  69686. };
  69687. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  69688. var _this = this;
  69689. var engine = this._scene.getEngine();
  69690. var targetSize = this._mapSize / this.blurScale;
  69691. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  69692. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  69693. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69694. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69695. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69696. }
  69697. if (this.useKernelBlur) {
  69698. 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);
  69699. this._kernelBlurXPostprocess.width = targetSize;
  69700. this._kernelBlurXPostprocess.height = targetSize;
  69701. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  69702. effect.setTexture("textureSampler", _this._shadowMap);
  69703. });
  69704. 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);
  69705. this._kernelBlurXPostprocess.autoClear = false;
  69706. this._kernelBlurYPostprocess.autoClear = false;
  69707. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  69708. this._kernelBlurXPostprocess.packedFloat = true;
  69709. this._kernelBlurYPostprocess.packedFloat = true;
  69710. }
  69711. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  69712. }
  69713. else {
  69714. 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);
  69715. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  69716. effect.setFloat2("screenSize", targetSize, targetSize);
  69717. effect.setTexture("textureSampler", _this._shadowMap);
  69718. });
  69719. this._boxBlurPostprocess.autoClear = false;
  69720. this._blurPostProcesses = [this._boxBlurPostprocess];
  69721. }
  69722. };
  69723. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69724. var index;
  69725. var engine = this._scene.getEngine();
  69726. if (depthOnlySubMeshes.length) {
  69727. engine.setColorWrite(false);
  69728. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69729. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  69730. }
  69731. engine.setColorWrite(true);
  69732. }
  69733. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69734. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  69735. }
  69736. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69737. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  69738. }
  69739. if (this._transparencyShadow) {
  69740. for (index = 0; index < transparentSubMeshes.length; index++) {
  69741. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  69742. }
  69743. }
  69744. };
  69745. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  69746. var _this = this;
  69747. var mesh = subMesh.getRenderingMesh();
  69748. var scene = this._scene;
  69749. var engine = scene.getEngine();
  69750. var material = subMesh.getMaterial();
  69751. if (!material) {
  69752. return;
  69753. }
  69754. // Culling
  69755. engine.setState(material.backFaceCulling);
  69756. // Managing instances
  69757. var batch = mesh._getInstancesRenderList(subMesh._id);
  69758. if (batch.mustReturn) {
  69759. return;
  69760. }
  69761. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  69762. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  69763. engine.enableEffect(this._effect);
  69764. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  69765. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  69766. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  69767. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  69768. this._effect.setVector3("lightData", this._cachedDirection);
  69769. }
  69770. else {
  69771. this._effect.setVector3("lightData", this._cachedPosition);
  69772. }
  69773. if (scene.activeCamera) {
  69774. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  69775. }
  69776. // Alpha test
  69777. if (material && material.needAlphaTesting()) {
  69778. var alphaTexture = material.getAlphaTestTexture();
  69779. if (alphaTexture) {
  69780. this._effect.setTexture("diffuseSampler", alphaTexture);
  69781. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  69782. }
  69783. }
  69784. // Bones
  69785. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69786. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  69787. }
  69788. // Morph targets
  69789. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  69790. if (this.forceBackFacesOnly) {
  69791. engine.setState(true, 0, false, true);
  69792. }
  69793. // Draw
  69794. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  69795. if (this.forceBackFacesOnly) {
  69796. engine.setState(true, 0, false, false);
  69797. }
  69798. }
  69799. else {
  69800. // Need to reset refresh rate of the shadowMap
  69801. if (this._shadowMap) {
  69802. this._shadowMap.resetRefreshCounter();
  69803. }
  69804. }
  69805. };
  69806. ShadowGenerator.prototype._applyFilterValues = function () {
  69807. if (!this._shadowMap) {
  69808. return;
  69809. }
  69810. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  69811. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  69812. }
  69813. else {
  69814. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69815. }
  69816. };
  69817. /**
  69818. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  69819. * @param onCompiled Callback triggered at the and of the effects compilation
  69820. * @param options Sets of optional options forcing the compilation with different modes
  69821. */
  69822. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  69823. var _this = this;
  69824. var localOptions = __assign({ useInstances: false }, options);
  69825. var shadowMap = this.getShadowMap();
  69826. if (!shadowMap) {
  69827. if (onCompiled) {
  69828. onCompiled(this);
  69829. }
  69830. return;
  69831. }
  69832. var renderList = shadowMap.renderList;
  69833. if (!renderList) {
  69834. if (onCompiled) {
  69835. onCompiled(this);
  69836. }
  69837. return;
  69838. }
  69839. var subMeshes = new Array();
  69840. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  69841. var mesh = renderList_1[_i];
  69842. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  69843. }
  69844. if (subMeshes.length === 0) {
  69845. if (onCompiled) {
  69846. onCompiled(this);
  69847. }
  69848. return;
  69849. }
  69850. var currentIndex = 0;
  69851. var checkReady = function () {
  69852. if (!_this._scene || !_this._scene.getEngine()) {
  69853. return;
  69854. }
  69855. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  69856. currentIndex++;
  69857. if (currentIndex >= subMeshes.length) {
  69858. if (onCompiled) {
  69859. onCompiled(_this);
  69860. }
  69861. return;
  69862. }
  69863. }
  69864. setTimeout(checkReady, 16);
  69865. };
  69866. checkReady();
  69867. };
  69868. /**
  69869. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  69870. * @param options Sets of optional options forcing the compilation with different modes
  69871. * @returns A promise that resolves when the compilation completes
  69872. */
  69873. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  69874. var _this = this;
  69875. return new Promise(function (resolve) {
  69876. _this.forceCompilation(function () {
  69877. resolve();
  69878. }, options);
  69879. });
  69880. };
  69881. /**
  69882. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  69883. * @param subMesh The submesh we want to render in the shadow map
  69884. * @param useInstances Defines wether will draw in the map using instances
  69885. * @returns true if ready otherwise, false
  69886. */
  69887. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  69888. var defines = [];
  69889. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  69890. defines.push("#define FLOAT");
  69891. }
  69892. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  69893. defines.push("#define ESM");
  69894. }
  69895. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  69896. defines.push("#define DEPTHTEXTURE");
  69897. }
  69898. var attribs = [BABYLON.VertexBuffer.PositionKind];
  69899. var mesh = subMesh.getMesh();
  69900. var material = subMesh.getMaterial();
  69901. // Normal bias.
  69902. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  69903. attribs.push(BABYLON.VertexBuffer.NormalKind);
  69904. defines.push("#define NORMAL");
  69905. if (mesh.nonUniformScaling) {
  69906. defines.push("#define NONUNIFORMSCALING");
  69907. }
  69908. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  69909. defines.push("#define DIRECTIONINLIGHTDATA");
  69910. }
  69911. }
  69912. // Alpha test
  69913. if (material && material.needAlphaTesting()) {
  69914. var alphaTexture = material.getAlphaTestTexture();
  69915. if (alphaTexture) {
  69916. defines.push("#define ALPHATEST");
  69917. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69918. attribs.push(BABYLON.VertexBuffer.UVKind);
  69919. defines.push("#define UV1");
  69920. }
  69921. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69922. if (alphaTexture.coordinatesIndex === 1) {
  69923. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69924. defines.push("#define UV2");
  69925. }
  69926. }
  69927. }
  69928. }
  69929. // Bones
  69930. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69931. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69932. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69933. if (mesh.numBoneInfluencers > 4) {
  69934. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69935. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69936. }
  69937. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69938. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  69939. }
  69940. else {
  69941. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69942. }
  69943. // Morph targets
  69944. var manager = mesh.morphTargetManager;
  69945. var morphInfluencers = 0;
  69946. if (manager) {
  69947. if (manager.numInfluencers > 0) {
  69948. defines.push("#define MORPHTARGETS");
  69949. morphInfluencers = manager.numInfluencers;
  69950. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  69951. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  69952. }
  69953. }
  69954. // Instances
  69955. if (useInstances) {
  69956. defines.push("#define INSTANCES");
  69957. attribs.push("world0");
  69958. attribs.push("world1");
  69959. attribs.push("world2");
  69960. attribs.push("world3");
  69961. }
  69962. // Get correct effect
  69963. var join = defines.join("\n");
  69964. if (this._cachedDefines !== join) {
  69965. this._cachedDefines = join;
  69966. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  69967. }
  69968. if (!this._effect.isReady()) {
  69969. return false;
  69970. }
  69971. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  69972. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  69973. this._initializeBlurRTTAndPostProcesses();
  69974. }
  69975. }
  69976. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  69977. return false;
  69978. }
  69979. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  69980. return false;
  69981. }
  69982. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  69983. return false;
  69984. }
  69985. return true;
  69986. };
  69987. /**
  69988. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  69989. * @param defines Defines of the material we want to update
  69990. * @param lightIndex Index of the light in the enabled light list of the material
  69991. */
  69992. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  69993. var scene = this._scene;
  69994. var light = this._light;
  69995. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  69996. return;
  69997. }
  69998. defines["SHADOW" + lightIndex] = true;
  69999. if (this.useContactHardeningShadow) {
  70000. defines["SHADOWPCSS" + lightIndex] = true;
  70001. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  70002. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  70003. }
  70004. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  70005. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  70006. }
  70007. // else default to high.
  70008. }
  70009. if (this.usePercentageCloserFiltering) {
  70010. defines["SHADOWPCF" + lightIndex] = true;
  70011. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  70012. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  70013. }
  70014. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  70015. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  70016. }
  70017. // else default to high.
  70018. }
  70019. else if (this.usePoissonSampling) {
  70020. defines["SHADOWPOISSON" + lightIndex] = true;
  70021. }
  70022. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  70023. defines["SHADOWESM" + lightIndex] = true;
  70024. }
  70025. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  70026. defines["SHADOWCLOSEESM" + lightIndex] = true;
  70027. }
  70028. if (light.needCube()) {
  70029. defines["SHADOWCUBE" + lightIndex] = true;
  70030. }
  70031. };
  70032. /**
  70033. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  70034. * defined in the generator but impacting the effect).
  70035. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  70036. * @param effect The effect we are binfing the information for
  70037. */
  70038. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  70039. var light = this._light;
  70040. var scene = this._scene;
  70041. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  70042. return;
  70043. }
  70044. var camera = scene.activeCamera;
  70045. if (!camera) {
  70046. return;
  70047. }
  70048. var shadowMap = this.getShadowMap();
  70049. if (!shadowMap) {
  70050. return;
  70051. }
  70052. if (!light.needCube()) {
  70053. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  70054. }
  70055. // Only PCF uses depth stencil texture.
  70056. if (this._filter === ShadowGenerator.FILTER_PCF) {
  70057. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  70058. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  70059. }
  70060. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  70061. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  70062. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  70063. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  70064. }
  70065. else {
  70066. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  70067. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  70068. }
  70069. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  70070. };
  70071. /**
  70072. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  70073. * (eq to shadow prjection matrix * light transform matrix)
  70074. * @returns The transform matrix used to create the shadow map
  70075. */
  70076. ShadowGenerator.prototype.getTransformMatrix = function () {
  70077. var scene = this._scene;
  70078. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  70079. return this._transformMatrix;
  70080. }
  70081. this._currentRenderID = scene.getRenderId();
  70082. this._currentFaceIndexCache = this._currentFaceIndex;
  70083. var lightPosition = this._light.position;
  70084. if (this._light.computeTransformedInformation()) {
  70085. lightPosition = this._light.transformedPosition;
  70086. }
  70087. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  70088. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  70089. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  70090. }
  70091. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  70092. this._cachedPosition.copyFrom(lightPosition);
  70093. this._cachedDirection.copyFrom(this._lightDirection);
  70094. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  70095. var shadowMap = this.getShadowMap();
  70096. if (shadowMap) {
  70097. var renderList = shadowMap.renderList;
  70098. if (renderList) {
  70099. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  70100. }
  70101. }
  70102. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  70103. }
  70104. return this._transformMatrix;
  70105. };
  70106. /**
  70107. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  70108. * Cube and 2D textures for instance.
  70109. */
  70110. ShadowGenerator.prototype.recreateShadowMap = function () {
  70111. var shadowMap = this._shadowMap;
  70112. if (!shadowMap) {
  70113. return;
  70114. }
  70115. // Track render list.
  70116. var renderList = shadowMap.renderList;
  70117. // Clean up existing data.
  70118. this._disposeRTTandPostProcesses();
  70119. // Reinitializes.
  70120. this._initializeGenerator();
  70121. // Reaffect the filter to ensure a correct fallback if necessary.
  70122. this.filter = this.filter;
  70123. // Reaffect the filter.
  70124. this._applyFilterValues();
  70125. // Reaffect Render List.
  70126. this._shadowMap.renderList = renderList;
  70127. };
  70128. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  70129. if (this._shadowMap2) {
  70130. this._shadowMap2.dispose();
  70131. this._shadowMap2 = null;
  70132. }
  70133. if (this._boxBlurPostprocess) {
  70134. this._boxBlurPostprocess.dispose();
  70135. this._boxBlurPostprocess = null;
  70136. }
  70137. if (this._kernelBlurXPostprocess) {
  70138. this._kernelBlurXPostprocess.dispose();
  70139. this._kernelBlurXPostprocess = null;
  70140. }
  70141. if (this._kernelBlurYPostprocess) {
  70142. this._kernelBlurYPostprocess.dispose();
  70143. this._kernelBlurYPostprocess = null;
  70144. }
  70145. this._blurPostProcesses = [];
  70146. };
  70147. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  70148. if (this._shadowMap) {
  70149. this._shadowMap.dispose();
  70150. this._shadowMap = null;
  70151. }
  70152. this._disposeBlurPostProcesses();
  70153. };
  70154. /**
  70155. * Disposes the ShadowGenerator.
  70156. * Returns nothing.
  70157. */
  70158. ShadowGenerator.prototype.dispose = function () {
  70159. this._disposeRTTandPostProcesses();
  70160. if (this._light) {
  70161. this._light._shadowGenerator = null;
  70162. this._light._markMeshesAsLightDirty();
  70163. }
  70164. };
  70165. /**
  70166. * Serializes the shadow generator setup to a json object.
  70167. * @returns The serialized JSON object
  70168. */
  70169. ShadowGenerator.prototype.serialize = function () {
  70170. var serializationObject = {};
  70171. var shadowMap = this.getShadowMap();
  70172. if (!shadowMap) {
  70173. return serializationObject;
  70174. }
  70175. serializationObject.lightId = this._light.id;
  70176. serializationObject.mapSize = shadowMap.getRenderSize();
  70177. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  70178. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  70179. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  70180. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  70181. serializationObject.usePoissonSampling = this.usePoissonSampling;
  70182. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  70183. serializationObject.depthScale = this.depthScale;
  70184. serializationObject.darkness = this.getDarkness();
  70185. serializationObject.blurBoxOffset = this.blurBoxOffset;
  70186. serializationObject.blurKernel = this.blurKernel;
  70187. serializationObject.blurScale = this.blurScale;
  70188. serializationObject.useKernelBlur = this.useKernelBlur;
  70189. serializationObject.transparencyShadow = this._transparencyShadow;
  70190. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  70191. serializationObject.bias = this.bias;
  70192. serializationObject.normalBias = this.normalBias;
  70193. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  70194. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  70195. serializationObject.filteringQuality = this.filteringQuality;
  70196. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  70197. serializationObject.renderList = [];
  70198. if (shadowMap.renderList) {
  70199. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  70200. var mesh = shadowMap.renderList[meshIndex];
  70201. serializationObject.renderList.push(mesh.id);
  70202. }
  70203. }
  70204. return serializationObject;
  70205. };
  70206. /**
  70207. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  70208. * @param parsedShadowGenerator The JSON object to parse
  70209. * @param scene The scene to create the shadow map for
  70210. * @returns The parsed shadow generator
  70211. */
  70212. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  70213. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  70214. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  70215. var shadowMap = shadowGenerator.getShadowMap();
  70216. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  70217. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  70218. meshes.forEach(function (mesh) {
  70219. if (!shadowMap) {
  70220. return;
  70221. }
  70222. if (!shadowMap.renderList) {
  70223. shadowMap.renderList = [];
  70224. }
  70225. shadowMap.renderList.push(mesh);
  70226. });
  70227. }
  70228. if (parsedShadowGenerator.usePoissonSampling) {
  70229. shadowGenerator.usePoissonSampling = true;
  70230. }
  70231. else if (parsedShadowGenerator.useExponentialShadowMap) {
  70232. shadowGenerator.useExponentialShadowMap = true;
  70233. }
  70234. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  70235. shadowGenerator.useBlurExponentialShadowMap = true;
  70236. }
  70237. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  70238. shadowGenerator.useCloseExponentialShadowMap = true;
  70239. }
  70240. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  70241. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  70242. }
  70243. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  70244. shadowGenerator.usePercentageCloserFiltering = true;
  70245. }
  70246. else if (parsedShadowGenerator.useContactHardeningShadow) {
  70247. shadowGenerator.useContactHardeningShadow = true;
  70248. }
  70249. if (parsedShadowGenerator.filteringQuality) {
  70250. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  70251. }
  70252. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  70253. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  70254. }
  70255. // Backward compat
  70256. else if (parsedShadowGenerator.useVarianceShadowMap) {
  70257. shadowGenerator.useExponentialShadowMap = true;
  70258. }
  70259. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  70260. shadowGenerator.useBlurExponentialShadowMap = true;
  70261. }
  70262. if (parsedShadowGenerator.depthScale) {
  70263. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  70264. }
  70265. if (parsedShadowGenerator.blurScale) {
  70266. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  70267. }
  70268. if (parsedShadowGenerator.blurBoxOffset) {
  70269. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  70270. }
  70271. if (parsedShadowGenerator.useKernelBlur) {
  70272. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  70273. }
  70274. if (parsedShadowGenerator.blurKernel) {
  70275. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  70276. }
  70277. if (parsedShadowGenerator.bias !== undefined) {
  70278. shadowGenerator.bias = parsedShadowGenerator.bias;
  70279. }
  70280. if (parsedShadowGenerator.normalBias !== undefined) {
  70281. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  70282. }
  70283. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  70284. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  70285. }
  70286. if (parsedShadowGenerator.darkness) {
  70287. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  70288. }
  70289. if (parsedShadowGenerator.transparencyShadow) {
  70290. shadowGenerator.setTransparencyShadow(true);
  70291. }
  70292. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  70293. return shadowGenerator;
  70294. };
  70295. /**
  70296. * Shadow generator mode None: no filtering applied.
  70297. */
  70298. ShadowGenerator.FILTER_NONE = 0;
  70299. /**
  70300. * Shadow generator mode ESM: Exponential Shadow Mapping.
  70301. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70302. */
  70303. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  70304. /**
  70305. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  70306. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  70307. */
  70308. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  70309. /**
  70310. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  70311. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70312. */
  70313. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  70314. /**
  70315. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  70316. * edge artifacts on steep falloff.
  70317. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70318. */
  70319. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  70320. /**
  70321. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  70322. * edge artifacts on steep falloff.
  70323. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70324. */
  70325. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  70326. /**
  70327. * Shadow generator mode PCF: Percentage Closer Filtering
  70328. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  70329. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  70330. */
  70331. ShadowGenerator.FILTER_PCF = 6;
  70332. /**
  70333. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  70334. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  70335. * Contact Hardening
  70336. */
  70337. ShadowGenerator.FILTER_PCSS = 7;
  70338. /**
  70339. * Reserved for PCF and PCSS
  70340. * Highest Quality.
  70341. *
  70342. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  70343. *
  70344. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  70345. */
  70346. ShadowGenerator.QUALITY_HIGH = 0;
  70347. /**
  70348. * Reserved for PCF and PCSS
  70349. * Good tradeoff for quality/perf cross devices
  70350. *
  70351. * Execute PCF on a 3*3 kernel.
  70352. *
  70353. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  70354. */
  70355. ShadowGenerator.QUALITY_MEDIUM = 1;
  70356. /**
  70357. * Reserved for PCF and PCSS
  70358. * The lowest quality but the fastest.
  70359. *
  70360. * Execute PCF on a 1*1 kernel.
  70361. *
  70362. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  70363. */
  70364. ShadowGenerator.QUALITY_LOW = 2;
  70365. return ShadowGenerator;
  70366. }());
  70367. BABYLON.ShadowGenerator = ShadowGenerator;
  70368. })(BABYLON || (BABYLON = {}));
  70369. //# sourceMappingURL=babylon.shadowGenerator.js.map
  70370. var BABYLON;
  70371. (function (BABYLON) {
  70372. var DefaultLoadingScreen = /** @class */ (function () {
  70373. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  70374. if (_loadingText === void 0) { _loadingText = ""; }
  70375. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  70376. var _this = this;
  70377. this._renderingCanvas = _renderingCanvas;
  70378. this._loadingText = _loadingText;
  70379. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  70380. // Resize
  70381. this._resizeLoadingUI = function () {
  70382. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  70383. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  70384. if (!_this._loadingDiv) {
  70385. return;
  70386. }
  70387. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  70388. _this._loadingDiv.style.left = canvasRect.left + "px";
  70389. _this._loadingDiv.style.top = canvasRect.top + "px";
  70390. _this._loadingDiv.style.width = canvasRect.width + "px";
  70391. _this._loadingDiv.style.height = canvasRect.height + "px";
  70392. };
  70393. }
  70394. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  70395. if (this._loadingDiv) {
  70396. // Do not add a loading screen if there is already one
  70397. return;
  70398. }
  70399. this._loadingDiv = document.createElement("div");
  70400. this._loadingDiv.id = "babylonjsLoadingDiv";
  70401. this._loadingDiv.style.opacity = "0";
  70402. this._loadingDiv.style.transition = "opacity 1.5s ease";
  70403. this._loadingDiv.style.pointerEvents = "none";
  70404. // Loading text
  70405. this._loadingTextDiv = document.createElement("div");
  70406. this._loadingTextDiv.style.position = "absolute";
  70407. this._loadingTextDiv.style.left = "0";
  70408. this._loadingTextDiv.style.top = "50%";
  70409. this._loadingTextDiv.style.marginTop = "80px";
  70410. this._loadingTextDiv.style.width = "100%";
  70411. this._loadingTextDiv.style.height = "20px";
  70412. this._loadingTextDiv.style.fontFamily = "Arial";
  70413. this._loadingTextDiv.style.fontSize = "14px";
  70414. this._loadingTextDiv.style.color = "white";
  70415. this._loadingTextDiv.style.textAlign = "center";
  70416. this._loadingTextDiv.innerHTML = "Loading";
  70417. this._loadingDiv.appendChild(this._loadingTextDiv);
  70418. //set the predefined text
  70419. this._loadingTextDiv.innerHTML = this._loadingText;
  70420. // Generating keyframes
  70421. var style = document.createElement('style');
  70422. style.type = 'text/css';
  70423. 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 }";
  70424. style.innerHTML = keyFrames;
  70425. document.getElementsByTagName('head')[0].appendChild(style);
  70426. // Loading img
  70427. var imgBack = new Image();
  70428. 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";
  70429. imgBack.style.position = "absolute";
  70430. imgBack.style.left = "50%";
  70431. imgBack.style.top = "50%";
  70432. imgBack.style.marginLeft = "-60px";
  70433. imgBack.style.marginTop = "-60px";
  70434. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  70435. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  70436. imgBack.style.transformOrigin = "50% 50%";
  70437. imgBack.style.webkitTransformOrigin = "50% 50%";
  70438. this._loadingDiv.appendChild(imgBack);
  70439. this._resizeLoadingUI();
  70440. window.addEventListener("resize", this._resizeLoadingUI);
  70441. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  70442. document.body.appendChild(this._loadingDiv);
  70443. this._loadingDiv.style.opacity = "1";
  70444. };
  70445. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  70446. var _this = this;
  70447. if (!this._loadingDiv) {
  70448. return;
  70449. }
  70450. var onTransitionEnd = function () {
  70451. if (!_this._loadingDiv) {
  70452. return;
  70453. }
  70454. document.body.removeChild(_this._loadingDiv);
  70455. window.removeEventListener("resize", _this._resizeLoadingUI);
  70456. _this._loadingDiv = null;
  70457. };
  70458. this._loadingDiv.style.opacity = "0";
  70459. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  70460. };
  70461. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  70462. set: function (text) {
  70463. this._loadingText = text;
  70464. if (this._loadingTextDiv) {
  70465. this._loadingTextDiv.innerHTML = this._loadingText;
  70466. }
  70467. },
  70468. enumerable: true,
  70469. configurable: true
  70470. });
  70471. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  70472. get: function () {
  70473. return this._loadingDivBackgroundColor;
  70474. },
  70475. set: function (color) {
  70476. this._loadingDivBackgroundColor = color;
  70477. if (!this._loadingDiv) {
  70478. return;
  70479. }
  70480. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  70481. },
  70482. enumerable: true,
  70483. configurable: true
  70484. });
  70485. return DefaultLoadingScreen;
  70486. }());
  70487. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  70488. })(BABYLON || (BABYLON = {}));
  70489. //# sourceMappingURL=babylon.loadingScreen.js.map
  70490. var BABYLON;
  70491. (function (BABYLON) {
  70492. var SceneLoaderProgressEvent = /** @class */ (function () {
  70493. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  70494. this.lengthComputable = lengthComputable;
  70495. this.loaded = loaded;
  70496. this.total = total;
  70497. }
  70498. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  70499. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  70500. };
  70501. return SceneLoaderProgressEvent;
  70502. }());
  70503. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  70504. var SceneLoader = /** @class */ (function () {
  70505. function SceneLoader() {
  70506. }
  70507. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  70508. get: function () {
  70509. return 0;
  70510. },
  70511. enumerable: true,
  70512. configurable: true
  70513. });
  70514. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  70515. get: function () {
  70516. return 1;
  70517. },
  70518. enumerable: true,
  70519. configurable: true
  70520. });
  70521. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  70522. get: function () {
  70523. return 2;
  70524. },
  70525. enumerable: true,
  70526. configurable: true
  70527. });
  70528. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  70529. get: function () {
  70530. return 3;
  70531. },
  70532. enumerable: true,
  70533. configurable: true
  70534. });
  70535. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  70536. get: function () {
  70537. return SceneLoader._ForceFullSceneLoadingForIncremental;
  70538. },
  70539. set: function (value) {
  70540. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  70541. },
  70542. enumerable: true,
  70543. configurable: true
  70544. });
  70545. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  70546. get: function () {
  70547. return SceneLoader._ShowLoadingScreen;
  70548. },
  70549. set: function (value) {
  70550. SceneLoader._ShowLoadingScreen = value;
  70551. },
  70552. enumerable: true,
  70553. configurable: true
  70554. });
  70555. Object.defineProperty(SceneLoader, "loggingLevel", {
  70556. get: function () {
  70557. return SceneLoader._loggingLevel;
  70558. },
  70559. set: function (value) {
  70560. SceneLoader._loggingLevel = value;
  70561. },
  70562. enumerable: true,
  70563. configurable: true
  70564. });
  70565. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  70566. get: function () {
  70567. return SceneLoader._CleanBoneMatrixWeights;
  70568. },
  70569. set: function (value) {
  70570. SceneLoader._CleanBoneMatrixWeights = value;
  70571. },
  70572. enumerable: true,
  70573. configurable: true
  70574. });
  70575. SceneLoader._getDefaultPlugin = function () {
  70576. return SceneLoader._registeredPlugins[".babylon"];
  70577. };
  70578. SceneLoader._getPluginForExtension = function (extension) {
  70579. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  70580. if (registeredPlugin) {
  70581. return registeredPlugin;
  70582. }
  70583. 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");
  70584. return SceneLoader._getDefaultPlugin();
  70585. };
  70586. SceneLoader._getPluginForDirectLoad = function (data) {
  70587. for (var extension in SceneLoader._registeredPlugins) {
  70588. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  70589. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  70590. return SceneLoader._registeredPlugins[extension];
  70591. }
  70592. }
  70593. return SceneLoader._getDefaultPlugin();
  70594. };
  70595. SceneLoader._getPluginForFilename = function (sceneFilename) {
  70596. if (sceneFilename.name) {
  70597. sceneFilename = sceneFilename.name;
  70598. }
  70599. var queryStringPosition = sceneFilename.indexOf("?");
  70600. if (queryStringPosition !== -1) {
  70601. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  70602. }
  70603. var dotPosition = sceneFilename.lastIndexOf(".");
  70604. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  70605. return SceneLoader._getPluginForExtension(extension);
  70606. };
  70607. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  70608. SceneLoader._getDirectLoad = function (sceneFilename) {
  70609. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  70610. return sceneFilename.substr(5);
  70611. }
  70612. return null;
  70613. };
  70614. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  70615. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  70616. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  70617. var plugin;
  70618. if (registeredPlugin.plugin.createPlugin) {
  70619. plugin = registeredPlugin.plugin.createPlugin();
  70620. }
  70621. else {
  70622. plugin = registeredPlugin.plugin;
  70623. }
  70624. var useArrayBuffer = registeredPlugin.isBinary;
  70625. var database;
  70626. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  70627. var dataCallback = function (data, responseURL) {
  70628. if (scene.isDisposed) {
  70629. onError("Scene has been disposed");
  70630. return;
  70631. }
  70632. scene.database = database;
  70633. onSuccess(plugin, data, responseURL);
  70634. };
  70635. var request = null;
  70636. var pluginDisposed = false;
  70637. var onDisposeObservable = plugin.onDisposeObservable;
  70638. if (onDisposeObservable) {
  70639. onDisposeObservable.add(function () {
  70640. pluginDisposed = true;
  70641. if (request) {
  70642. request.abort();
  70643. request = null;
  70644. }
  70645. onDispose();
  70646. });
  70647. }
  70648. var manifestChecked = function () {
  70649. if (pluginDisposed) {
  70650. return;
  70651. }
  70652. var url = rootUrl + sceneFilename;
  70653. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  70654. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  70655. } : undefined, database, useArrayBuffer, function (request, exception) {
  70656. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  70657. });
  70658. };
  70659. if (directLoad) {
  70660. dataCallback(directLoad);
  70661. return plugin;
  70662. }
  70663. if (rootUrl.indexOf("file:") === -1) {
  70664. var engine = scene.getEngine();
  70665. var canUseOfflineSupport = engine.enableOfflineSupport;
  70666. if (canUseOfflineSupport) {
  70667. // Also check for exceptions
  70668. var exceptionFound = false;
  70669. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  70670. var regex = _a[_i];
  70671. if (regex.test(rootUrl + sceneFilename)) {
  70672. exceptionFound = true;
  70673. break;
  70674. }
  70675. }
  70676. canUseOfflineSupport = !exceptionFound;
  70677. }
  70678. if (canUseOfflineSupport) {
  70679. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  70680. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  70681. }
  70682. else {
  70683. manifestChecked();
  70684. }
  70685. }
  70686. // Loading file from disk via input file or drag'n'drop
  70687. else {
  70688. var fileOrString = sceneFilename;
  70689. if (fileOrString.name) { // File
  70690. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  70691. }
  70692. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  70693. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  70694. }
  70695. else {
  70696. onError("Unable to find file named " + sceneFilename);
  70697. }
  70698. }
  70699. return plugin;
  70700. };
  70701. // Public functions
  70702. SceneLoader.GetPluginForExtension = function (extension) {
  70703. return SceneLoader._getPluginForExtension(extension).plugin;
  70704. };
  70705. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  70706. return !!SceneLoader._registeredPlugins[extension];
  70707. };
  70708. SceneLoader.RegisterPlugin = function (plugin) {
  70709. if (typeof plugin.extensions === "string") {
  70710. var extension = plugin.extensions;
  70711. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  70712. plugin: plugin,
  70713. isBinary: false
  70714. };
  70715. }
  70716. else {
  70717. var extensions = plugin.extensions;
  70718. Object.keys(extensions).forEach(function (extension) {
  70719. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  70720. plugin: plugin,
  70721. isBinary: extensions[extension].isBinary
  70722. };
  70723. });
  70724. }
  70725. };
  70726. /**
  70727. * Import meshes into a scene
  70728. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  70729. * @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)
  70730. * @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)
  70731. * @param scene the instance of BABYLON.Scene to append to
  70732. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  70733. * @param onProgress a callback with a progress event for each file being loaded
  70734. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70735. * @param pluginExtension the extension used to determine the plugin
  70736. * @returns The loaded plugin
  70737. */
  70738. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  70739. if (sceneFilename === void 0) { sceneFilename = ""; }
  70740. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70741. if (onSuccess === void 0) { onSuccess = null; }
  70742. if (onProgress === void 0) { onProgress = null; }
  70743. if (onError === void 0) { onError = null; }
  70744. if (pluginExtension === void 0) { pluginExtension = null; }
  70745. if (!scene) {
  70746. BABYLON.Tools.Error("No scene available to import mesh to");
  70747. return null;
  70748. }
  70749. if (!sceneFilename) {
  70750. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  70751. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  70752. }
  70753. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  70754. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  70755. return null;
  70756. }
  70757. var loadingToken = {};
  70758. scene._addPendingData(loadingToken);
  70759. var disposeHandler = function () {
  70760. scene._removePendingData(loadingToken);
  70761. };
  70762. var errorHandler = function (message, exception) {
  70763. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  70764. if (onError) {
  70765. onError(scene, errorMessage, exception);
  70766. }
  70767. else {
  70768. BABYLON.Tools.Error(errorMessage);
  70769. // should the exception be thrown?
  70770. }
  70771. disposeHandler();
  70772. };
  70773. var progressHandler = onProgress ? function (event) {
  70774. try {
  70775. onProgress(event);
  70776. }
  70777. catch (e) {
  70778. errorHandler("Error in onProgress callback", e);
  70779. }
  70780. } : undefined;
  70781. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  70782. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  70783. if (onSuccess) {
  70784. try {
  70785. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  70786. }
  70787. catch (e) {
  70788. errorHandler("Error in onSuccess callback", e);
  70789. }
  70790. }
  70791. scene._removePendingData(loadingToken);
  70792. };
  70793. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  70794. if (plugin.rewriteRootURL) {
  70795. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  70796. }
  70797. if (sceneFilename === "") {
  70798. if (sceneFilename === "") {
  70799. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  70800. }
  70801. }
  70802. if (plugin.importMesh) {
  70803. var syncedPlugin = plugin;
  70804. var meshes = new Array();
  70805. var particleSystems = new Array();
  70806. var skeletons = new Array();
  70807. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  70808. return;
  70809. }
  70810. scene.loadingPluginName = plugin.name;
  70811. successHandler(meshes, particleSystems, skeletons, []);
  70812. }
  70813. else {
  70814. var asyncedPlugin = plugin;
  70815. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  70816. scene.loadingPluginName = plugin.name;
  70817. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  70818. }).catch(function (error) {
  70819. errorHandler(error.message, error);
  70820. });
  70821. }
  70822. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  70823. };
  70824. /**
  70825. * Import meshes into a scene
  70826. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  70827. * @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)
  70828. * @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)
  70829. * @param scene the instance of BABYLON.Scene to append to
  70830. * @param onProgress a callback with a progress event for each file being loaded
  70831. * @param pluginExtension the extension used to determine the plugin
  70832. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  70833. */
  70834. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  70835. if (sceneFilename === void 0) { sceneFilename = ""; }
  70836. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70837. if (onProgress === void 0) { onProgress = null; }
  70838. if (pluginExtension === void 0) { pluginExtension = null; }
  70839. return new Promise(function (resolve, reject) {
  70840. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  70841. resolve({
  70842. meshes: meshes,
  70843. particleSystems: particleSystems,
  70844. skeletons: skeletons,
  70845. animationGroups: animationGroups
  70846. });
  70847. }, onProgress, function (scene, message, exception) {
  70848. reject(exception || new Error(message));
  70849. }, pluginExtension);
  70850. });
  70851. };
  70852. /**
  70853. * Load a scene
  70854. * @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)
  70855. * @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)
  70856. * @param engine is the instance of BABYLON.Engine to use to create the scene
  70857. * @param onSuccess a callback with the scene when import succeeds
  70858. * @param onProgress a callback with a progress event for each file being loaded
  70859. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70860. * @param pluginExtension the extension used to determine the plugin
  70861. * @returns The loaded plugin
  70862. */
  70863. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  70864. if (onSuccess === void 0) { onSuccess = null; }
  70865. if (onProgress === void 0) { onProgress = null; }
  70866. if (onError === void 0) { onError = null; }
  70867. if (pluginExtension === void 0) { pluginExtension = null; }
  70868. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  70869. };
  70870. /**
  70871. * Load a scene
  70872. * @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)
  70873. * @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)
  70874. * @param engine is the instance of BABYLON.Engine to use to create the scene
  70875. * @param onProgress a callback with a progress event for each file being loaded
  70876. * @param pluginExtension the extension used to determine the plugin
  70877. * @returns The loaded scene
  70878. */
  70879. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  70880. if (onProgress === void 0) { onProgress = null; }
  70881. if (pluginExtension === void 0) { pluginExtension = null; }
  70882. return new Promise(function (resolve, reject) {
  70883. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  70884. resolve(scene);
  70885. }, onProgress, function (scene, message, exception) {
  70886. reject(exception || new Error(message));
  70887. }, pluginExtension);
  70888. });
  70889. };
  70890. /**
  70891. * Append a scene
  70892. * @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)
  70893. * @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)
  70894. * @param scene is the instance of BABYLON.Scene to append to
  70895. * @param onSuccess a callback with the scene when import succeeds
  70896. * @param onProgress a callback with a progress event for each file being loaded
  70897. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70898. * @param pluginExtension the extension used to determine the plugin
  70899. * @returns The loaded plugin
  70900. */
  70901. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  70902. if (sceneFilename === void 0) { sceneFilename = ""; }
  70903. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70904. if (onSuccess === void 0) { onSuccess = null; }
  70905. if (onProgress === void 0) { onProgress = null; }
  70906. if (onError === void 0) { onError = null; }
  70907. if (pluginExtension === void 0) { pluginExtension = null; }
  70908. if (!scene) {
  70909. BABYLON.Tools.Error("No scene available to append to");
  70910. return null;
  70911. }
  70912. if (!sceneFilename) {
  70913. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  70914. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  70915. }
  70916. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  70917. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  70918. return null;
  70919. }
  70920. if (SceneLoader.ShowLoadingScreen) {
  70921. scene.getEngine().displayLoadingUI();
  70922. }
  70923. var loadingToken = {};
  70924. scene._addPendingData(loadingToken);
  70925. var disposeHandler = function () {
  70926. scene._removePendingData(loadingToken);
  70927. scene.getEngine().hideLoadingUI();
  70928. };
  70929. var errorHandler = function (message, exception) {
  70930. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  70931. if (onError) {
  70932. onError(scene, errorMessage, exception);
  70933. }
  70934. else {
  70935. BABYLON.Tools.Error(errorMessage);
  70936. // should the exception be thrown?
  70937. }
  70938. disposeHandler();
  70939. };
  70940. var progressHandler = onProgress ? function (event) {
  70941. try {
  70942. onProgress(event);
  70943. }
  70944. catch (e) {
  70945. errorHandler("Error in onProgress callback", e);
  70946. }
  70947. } : undefined;
  70948. var successHandler = function () {
  70949. if (onSuccess) {
  70950. try {
  70951. onSuccess(scene);
  70952. }
  70953. catch (e) {
  70954. errorHandler("Error in onSuccess callback", e);
  70955. }
  70956. }
  70957. scene._removePendingData(loadingToken);
  70958. };
  70959. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  70960. if (sceneFilename === "") {
  70961. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  70962. }
  70963. if (plugin.load) {
  70964. var syncedPlugin = plugin;
  70965. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  70966. return;
  70967. }
  70968. scene.loadingPluginName = plugin.name;
  70969. successHandler();
  70970. }
  70971. else {
  70972. var asyncedPlugin = plugin;
  70973. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  70974. scene.loadingPluginName = plugin.name;
  70975. successHandler();
  70976. }).catch(function (error) {
  70977. errorHandler(error.message, error);
  70978. });
  70979. }
  70980. if (SceneLoader.ShowLoadingScreen) {
  70981. scene.executeWhenReady(function () {
  70982. scene.getEngine().hideLoadingUI();
  70983. });
  70984. }
  70985. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  70986. };
  70987. /**
  70988. * Append a scene
  70989. * @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)
  70990. * @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)
  70991. * @param scene is the instance of BABYLON.Scene to append to
  70992. * @param onProgress a callback with a progress event for each file being loaded
  70993. * @param pluginExtension the extension used to determine the plugin
  70994. * @returns The given scene
  70995. */
  70996. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  70997. if (sceneFilename === void 0) { sceneFilename = ""; }
  70998. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70999. if (onProgress === void 0) { onProgress = null; }
  71000. if (pluginExtension === void 0) { pluginExtension = null; }
  71001. return new Promise(function (resolve, reject) {
  71002. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  71003. resolve(scene);
  71004. }, onProgress, function (scene, message, exception) {
  71005. reject(exception || new Error(message));
  71006. }, pluginExtension);
  71007. });
  71008. };
  71009. /**
  71010. * Load a scene into an asset container
  71011. * @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)
  71012. * @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)
  71013. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  71014. * @param onSuccess a callback with the scene when import succeeds
  71015. * @param onProgress a callback with a progress event for each file being loaded
  71016. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71017. * @param pluginExtension the extension used to determine the plugin
  71018. * @returns The loaded plugin
  71019. */
  71020. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  71021. if (sceneFilename === void 0) { sceneFilename = ""; }
  71022. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71023. if (onSuccess === void 0) { onSuccess = null; }
  71024. if (onProgress === void 0) { onProgress = null; }
  71025. if (onError === void 0) { onError = null; }
  71026. if (pluginExtension === void 0) { pluginExtension = null; }
  71027. if (!scene) {
  71028. BABYLON.Tools.Error("No scene available to load asset container to");
  71029. return null;
  71030. }
  71031. if (!sceneFilename) {
  71032. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  71033. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  71034. }
  71035. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  71036. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  71037. return null;
  71038. }
  71039. var loadingToken = {};
  71040. scene._addPendingData(loadingToken);
  71041. var disposeHandler = function () {
  71042. scene._removePendingData(loadingToken);
  71043. };
  71044. var errorHandler = function (message, exception) {
  71045. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  71046. if (onError) {
  71047. onError(scene, errorMessage, exception);
  71048. }
  71049. else {
  71050. BABYLON.Tools.Error(errorMessage);
  71051. // should the exception be thrown?
  71052. }
  71053. disposeHandler();
  71054. };
  71055. var progressHandler = onProgress ? function (event) {
  71056. try {
  71057. onProgress(event);
  71058. }
  71059. catch (e) {
  71060. errorHandler("Error in onProgress callback", e);
  71061. }
  71062. } : undefined;
  71063. var successHandler = function (assets) {
  71064. if (onSuccess) {
  71065. try {
  71066. onSuccess(assets);
  71067. }
  71068. catch (e) {
  71069. errorHandler("Error in onSuccess callback", e);
  71070. }
  71071. }
  71072. scene._removePendingData(loadingToken);
  71073. };
  71074. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  71075. if (plugin.loadAssetContainer) {
  71076. var syncedPlugin = plugin;
  71077. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  71078. if (!assetContainer) {
  71079. return;
  71080. }
  71081. scene.loadingPluginName = plugin.name;
  71082. successHandler(assetContainer);
  71083. }
  71084. else if (plugin.loadAssetContainerAsync) {
  71085. var asyncedPlugin = plugin;
  71086. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  71087. scene.loadingPluginName = plugin.name;
  71088. successHandler(assetContainer);
  71089. }).catch(function (error) {
  71090. errorHandler(error.message, error);
  71091. });
  71092. }
  71093. else {
  71094. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  71095. }
  71096. if (SceneLoader.ShowLoadingScreen) {
  71097. scene.executeWhenReady(function () {
  71098. scene.getEngine().hideLoadingUI();
  71099. });
  71100. }
  71101. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  71102. };
  71103. /**
  71104. * Load a scene into an asset container
  71105. * @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)
  71106. * @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)
  71107. * @param scene is the instance of BABYLON.Scene to append to
  71108. * @param onProgress a callback with a progress event for each file being loaded
  71109. * @param pluginExtension the extension used to determine the plugin
  71110. * @returns The loaded asset container
  71111. */
  71112. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  71113. if (sceneFilename === void 0) { sceneFilename = ""; }
  71114. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71115. if (onProgress === void 0) { onProgress = null; }
  71116. if (pluginExtension === void 0) { pluginExtension = null; }
  71117. return new Promise(function (resolve, reject) {
  71118. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  71119. resolve(assetContainer);
  71120. }, onProgress, function (scene, message, exception) {
  71121. reject(exception || new Error(message));
  71122. }, pluginExtension);
  71123. });
  71124. };
  71125. // Flags
  71126. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  71127. SceneLoader._ShowLoadingScreen = true;
  71128. SceneLoader._CleanBoneMatrixWeights = false;
  71129. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  71130. // Members
  71131. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  71132. SceneLoader._registeredPlugins = {};
  71133. return SceneLoader;
  71134. }());
  71135. BABYLON.SceneLoader = SceneLoader;
  71136. ;
  71137. })(BABYLON || (BABYLON = {}));
  71138. //# sourceMappingURL=babylon.sceneLoader.js.map
  71139. var BABYLON;
  71140. (function (BABYLON) {
  71141. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  71142. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  71143. var parsedMaterial = parsedData.materials[index];
  71144. if (parsedMaterial.id === id) {
  71145. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  71146. }
  71147. }
  71148. return null;
  71149. };
  71150. var isDescendantOf = function (mesh, names, hierarchyIds) {
  71151. for (var i in names) {
  71152. if (mesh.name === names[i]) {
  71153. hierarchyIds.push(mesh.id);
  71154. return true;
  71155. }
  71156. }
  71157. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  71158. hierarchyIds.push(mesh.id);
  71159. return true;
  71160. }
  71161. return false;
  71162. };
  71163. var logOperation = function (operation, producer) {
  71164. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  71165. };
  71166. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  71167. if (addToScene === void 0) { addToScene = false; }
  71168. var container = new BABYLON.AssetContainer(scene);
  71169. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  71170. // when SceneLoader.debugLogging = true (default), or exception encountered.
  71171. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  71172. // and avoid problems with multiple concurrent .babylon loads.
  71173. var log = "importScene has failed JSON parse";
  71174. try {
  71175. var parsedData = JSON.parse(data);
  71176. log = "";
  71177. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  71178. var index;
  71179. var cache;
  71180. // Lights
  71181. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  71182. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  71183. var parsedLight = parsedData.lights[index];
  71184. var light = BABYLON.Light.Parse(parsedLight, scene);
  71185. if (light) {
  71186. container.lights.push(light);
  71187. log += (index === 0 ? "\n\tLights:" : "");
  71188. log += "\n\t\t" + light.toString(fullDetails);
  71189. }
  71190. }
  71191. }
  71192. // Animations
  71193. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  71194. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  71195. var parsedAnimation = parsedData.animations[index];
  71196. var animation = BABYLON.Animation.Parse(parsedAnimation);
  71197. scene.animations.push(animation);
  71198. container.animations.push(animation);
  71199. log += (index === 0 ? "\n\tAnimations:" : "");
  71200. log += "\n\t\t" + animation.toString(fullDetails);
  71201. }
  71202. }
  71203. // Materials
  71204. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  71205. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  71206. var parsedMaterial = parsedData.materials[index];
  71207. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  71208. container.materials.push(mat);
  71209. log += (index === 0 ? "\n\tMaterials:" : "");
  71210. log += "\n\t\t" + mat.toString(fullDetails);
  71211. }
  71212. }
  71213. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  71214. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  71215. var parsedMultiMaterial = parsedData.multiMaterials[index];
  71216. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  71217. container.multiMaterials.push(mmat);
  71218. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  71219. log += "\n\t\t" + mmat.toString(fullDetails);
  71220. }
  71221. }
  71222. // Morph targets
  71223. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  71224. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  71225. var managerData = _a[_i];
  71226. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  71227. }
  71228. }
  71229. // Skeletons
  71230. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  71231. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  71232. var parsedSkeleton = parsedData.skeletons[index];
  71233. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  71234. container.skeletons.push(skeleton);
  71235. log += (index === 0 ? "\n\tSkeletons:" : "");
  71236. log += "\n\t\t" + skeleton.toString(fullDetails);
  71237. }
  71238. }
  71239. // Geometries
  71240. var geometries = parsedData.geometries;
  71241. if (geometries !== undefined && geometries !== null) {
  71242. var addedGeometry = new Array();
  71243. // Boxes
  71244. var boxes = geometries.boxes;
  71245. if (boxes !== undefined && boxes !== null) {
  71246. for (index = 0, cache = boxes.length; index < cache; index++) {
  71247. var parsedBox = boxes[index];
  71248. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  71249. }
  71250. }
  71251. // Spheres
  71252. var spheres = geometries.spheres;
  71253. if (spheres !== undefined && spheres !== null) {
  71254. for (index = 0, cache = spheres.length; index < cache; index++) {
  71255. var parsedSphere = spheres[index];
  71256. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  71257. }
  71258. }
  71259. // Cylinders
  71260. var cylinders = geometries.cylinders;
  71261. if (cylinders !== undefined && cylinders !== null) {
  71262. for (index = 0, cache = cylinders.length; index < cache; index++) {
  71263. var parsedCylinder = cylinders[index];
  71264. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  71265. }
  71266. }
  71267. // Toruses
  71268. var toruses = geometries.toruses;
  71269. if (toruses !== undefined && toruses !== null) {
  71270. for (index = 0, cache = toruses.length; index < cache; index++) {
  71271. var parsedTorus = toruses[index];
  71272. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  71273. }
  71274. }
  71275. // Grounds
  71276. var grounds = geometries.grounds;
  71277. if (grounds !== undefined && grounds !== null) {
  71278. for (index = 0, cache = grounds.length; index < cache; index++) {
  71279. var parsedGround = grounds[index];
  71280. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  71281. }
  71282. }
  71283. // Planes
  71284. var planes = geometries.planes;
  71285. if (planes !== undefined && planes !== null) {
  71286. for (index = 0, cache = planes.length; index < cache; index++) {
  71287. var parsedPlane = planes[index];
  71288. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  71289. }
  71290. }
  71291. // TorusKnots
  71292. var torusKnots = geometries.torusKnots;
  71293. if (torusKnots !== undefined && torusKnots !== null) {
  71294. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  71295. var parsedTorusKnot = torusKnots[index];
  71296. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  71297. }
  71298. }
  71299. // VertexData
  71300. var vertexData = geometries.vertexData;
  71301. if (vertexData !== undefined && vertexData !== null) {
  71302. for (index = 0, cache = vertexData.length; index < cache; index++) {
  71303. var parsedVertexData = vertexData[index];
  71304. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  71305. }
  71306. }
  71307. addedGeometry.forEach(function (g) {
  71308. if (g) {
  71309. container.geometries.push(g);
  71310. }
  71311. });
  71312. }
  71313. // Transform nodes
  71314. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  71315. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  71316. var parsedTransformNode = parsedData.transformNodes[index];
  71317. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  71318. container.transformNodes.push(node);
  71319. }
  71320. }
  71321. // Meshes
  71322. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  71323. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  71324. var parsedMesh = parsedData.meshes[index];
  71325. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  71326. container.meshes.push(mesh);
  71327. log += (index === 0 ? "\n\tMeshes:" : "");
  71328. log += "\n\t\t" + mesh.toString(fullDetails);
  71329. }
  71330. }
  71331. // Cameras
  71332. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  71333. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  71334. var parsedCamera = parsedData.cameras[index];
  71335. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  71336. container.cameras.push(camera);
  71337. log += (index === 0 ? "\n\tCameras:" : "");
  71338. log += "\n\t\t" + camera.toString(fullDetails);
  71339. }
  71340. }
  71341. // Browsing all the graph to connect the dots
  71342. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  71343. var camera = scene.cameras[index];
  71344. if (camera._waitingParentId) {
  71345. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  71346. camera._waitingParentId = null;
  71347. }
  71348. }
  71349. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  71350. var light_1 = scene.lights[index];
  71351. if (light_1 && light_1._waitingParentId) {
  71352. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  71353. light_1._waitingParentId = null;
  71354. }
  71355. }
  71356. // Sounds
  71357. // TODO: add sound
  71358. var loadedSounds = [];
  71359. var loadedSound;
  71360. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  71361. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  71362. var parsedSound = parsedData.sounds[index];
  71363. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71364. if (!parsedSound.url)
  71365. parsedSound.url = parsedSound.name;
  71366. if (!loadedSounds[parsedSound.url]) {
  71367. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  71368. loadedSounds[parsedSound.url] = loadedSound;
  71369. container.sounds.push(loadedSound);
  71370. }
  71371. else {
  71372. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  71373. }
  71374. }
  71375. else {
  71376. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  71377. }
  71378. }
  71379. }
  71380. loadedSounds = [];
  71381. // Connect parents & children and parse actions
  71382. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  71383. var transformNode = scene.transformNodes[index];
  71384. if (transformNode._waitingParentId) {
  71385. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  71386. transformNode._waitingParentId = null;
  71387. }
  71388. }
  71389. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71390. var mesh = scene.meshes[index];
  71391. if (mesh._waitingParentId) {
  71392. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  71393. mesh._waitingParentId = null;
  71394. }
  71395. if (mesh._waitingActions) {
  71396. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  71397. mesh._waitingActions = null;
  71398. }
  71399. }
  71400. // freeze world matrix application
  71401. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71402. var currentMesh = scene.meshes[index];
  71403. if (currentMesh._waitingFreezeWorldMatrix) {
  71404. currentMesh.freezeWorldMatrix();
  71405. currentMesh._waitingFreezeWorldMatrix = null;
  71406. }
  71407. else {
  71408. currentMesh.computeWorldMatrix(true);
  71409. }
  71410. }
  71411. // Shadows
  71412. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  71413. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  71414. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  71415. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  71416. // SG would be available on their associated lights
  71417. }
  71418. }
  71419. // Lights exclusions / inclusions
  71420. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  71421. var light_2 = scene.lights[index];
  71422. // Excluded check
  71423. if (light_2._excludedMeshesIds.length > 0) {
  71424. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  71425. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  71426. if (excludedMesh) {
  71427. light_2.excludedMeshes.push(excludedMesh);
  71428. }
  71429. }
  71430. light_2._excludedMeshesIds = [];
  71431. }
  71432. // Included check
  71433. if (light_2._includedOnlyMeshesIds.length > 0) {
  71434. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  71435. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  71436. if (includedOnlyMesh) {
  71437. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  71438. }
  71439. }
  71440. light_2._includedOnlyMeshesIds = [];
  71441. }
  71442. }
  71443. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  71444. // Actions (scene)
  71445. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  71446. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  71447. }
  71448. if (!addToScene) {
  71449. container.removeAllFromScene();
  71450. }
  71451. }
  71452. catch (err) {
  71453. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  71454. if (onError) {
  71455. onError(msg, err);
  71456. }
  71457. else {
  71458. BABYLON.Tools.Log(msg);
  71459. throw err;
  71460. }
  71461. }
  71462. finally {
  71463. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  71464. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  71465. }
  71466. }
  71467. return container;
  71468. };
  71469. BABYLON.SceneLoader.RegisterPlugin({
  71470. name: "babylon.js",
  71471. extensions: ".babylon",
  71472. canDirectLoad: function (data) {
  71473. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  71474. return true;
  71475. }
  71476. return false;
  71477. },
  71478. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  71479. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  71480. // when SceneLoader.debugLogging = true (default), or exception encountered.
  71481. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  71482. // and avoid problems with multiple concurrent .babylon loads.
  71483. var log = "importMesh has failed JSON parse";
  71484. try {
  71485. var parsedData = JSON.parse(data);
  71486. log = "";
  71487. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  71488. if (!meshesNames) {
  71489. meshesNames = null;
  71490. }
  71491. else if (!Array.isArray(meshesNames)) {
  71492. meshesNames = [meshesNames];
  71493. }
  71494. var hierarchyIds = new Array();
  71495. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  71496. var loadedSkeletonsIds = [];
  71497. var loadedMaterialsIds = [];
  71498. var index;
  71499. var cache;
  71500. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  71501. var parsedMesh = parsedData.meshes[index];
  71502. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  71503. if (meshesNames !== null) {
  71504. // Remove found mesh name from list.
  71505. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  71506. }
  71507. //Geometry?
  71508. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  71509. //does the file contain geometries?
  71510. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  71511. //find the correct geometry and add it to the scene
  71512. var found = false;
  71513. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  71514. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  71515. return;
  71516. }
  71517. else {
  71518. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  71519. if (parsedGeometryData.id === parsedMesh.geometryId) {
  71520. switch (geometryType) {
  71521. case "boxes":
  71522. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  71523. break;
  71524. case "spheres":
  71525. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  71526. break;
  71527. case "cylinders":
  71528. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  71529. break;
  71530. case "toruses":
  71531. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  71532. break;
  71533. case "grounds":
  71534. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  71535. break;
  71536. case "planes":
  71537. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  71538. break;
  71539. case "torusKnots":
  71540. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  71541. break;
  71542. case "vertexData":
  71543. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  71544. break;
  71545. }
  71546. found = true;
  71547. }
  71548. });
  71549. }
  71550. });
  71551. if (found === false) {
  71552. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  71553. }
  71554. }
  71555. }
  71556. // Material ?
  71557. if (parsedMesh.materialId) {
  71558. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  71559. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  71560. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  71561. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  71562. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  71563. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  71564. var subMatId = parsedMultiMaterial.materials[matIndex];
  71565. loadedMaterialsIds.push(subMatId);
  71566. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  71567. if (mat) {
  71568. log += "\n\tMaterial " + mat.toString(fullDetails);
  71569. }
  71570. }
  71571. loadedMaterialsIds.push(parsedMultiMaterial.id);
  71572. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  71573. if (mmat) {
  71574. materialFound = true;
  71575. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  71576. }
  71577. break;
  71578. }
  71579. }
  71580. }
  71581. if (materialFound === false) {
  71582. loadedMaterialsIds.push(parsedMesh.materialId);
  71583. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  71584. if (!mat) {
  71585. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  71586. }
  71587. else {
  71588. log += "\n\tMaterial " + mat.toString(fullDetails);
  71589. }
  71590. }
  71591. }
  71592. // Skeleton ?
  71593. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  71594. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  71595. if (skeletonAlreadyLoaded === false) {
  71596. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  71597. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  71598. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  71599. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  71600. skeletons.push(skeleton);
  71601. loadedSkeletonsIds.push(parsedSkeleton.id);
  71602. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  71603. }
  71604. }
  71605. }
  71606. }
  71607. // Morph targets ?
  71608. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  71609. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  71610. var managerData = _a[_i];
  71611. BABYLON.MorphTargetManager.Parse(managerData, scene);
  71612. }
  71613. }
  71614. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  71615. meshes.push(mesh);
  71616. log += "\n\tMesh " + mesh.toString(fullDetails);
  71617. }
  71618. }
  71619. // Connecting parents
  71620. var currentMesh;
  71621. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71622. currentMesh = scene.meshes[index];
  71623. if (currentMesh._waitingParentId) {
  71624. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  71625. currentMesh._waitingParentId = null;
  71626. }
  71627. }
  71628. // freeze and compute world matrix application
  71629. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71630. currentMesh = scene.meshes[index];
  71631. if (currentMesh._waitingFreezeWorldMatrix) {
  71632. currentMesh.freezeWorldMatrix();
  71633. currentMesh._waitingFreezeWorldMatrix = null;
  71634. }
  71635. else {
  71636. currentMesh.computeWorldMatrix(true);
  71637. }
  71638. }
  71639. }
  71640. // Particles
  71641. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  71642. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  71643. if (parser) {
  71644. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  71645. var parsedParticleSystem = parsedData.particleSystems[index];
  71646. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  71647. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  71648. }
  71649. }
  71650. }
  71651. }
  71652. return true;
  71653. }
  71654. catch (err) {
  71655. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  71656. if (onError) {
  71657. onError(msg, err);
  71658. }
  71659. else {
  71660. BABYLON.Tools.Log(msg);
  71661. throw err;
  71662. }
  71663. }
  71664. finally {
  71665. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  71666. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  71667. }
  71668. }
  71669. return false;
  71670. },
  71671. load: function (scene, data, rootUrl, onError) {
  71672. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  71673. // when SceneLoader.debugLogging = true (default), or exception encountered.
  71674. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  71675. // and avoid problems with multiple concurrent .babylon loads.
  71676. var log = "importScene has failed JSON parse";
  71677. try {
  71678. var parsedData = JSON.parse(data);
  71679. log = "";
  71680. // Scene
  71681. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  71682. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  71683. }
  71684. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  71685. scene.autoClear = parsedData.autoClear;
  71686. }
  71687. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  71688. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  71689. }
  71690. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  71691. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  71692. }
  71693. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  71694. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  71695. }
  71696. // Fog
  71697. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  71698. scene.fogMode = parsedData.fogMode;
  71699. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  71700. scene.fogStart = parsedData.fogStart;
  71701. scene.fogEnd = parsedData.fogEnd;
  71702. scene.fogDensity = parsedData.fogDensity;
  71703. log += "\tFog mode for scene: ";
  71704. switch (scene.fogMode) {
  71705. // getters not compiling, so using hardcoded
  71706. case 1:
  71707. log += "exp\n";
  71708. break;
  71709. case 2:
  71710. log += "exp2\n";
  71711. break;
  71712. case 3:
  71713. log += "linear\n";
  71714. break;
  71715. }
  71716. }
  71717. //Physics
  71718. if (parsedData.physicsEnabled) {
  71719. var physicsPlugin;
  71720. if (parsedData.physicsEngine === "cannon") {
  71721. physicsPlugin = new BABYLON.CannonJSPlugin();
  71722. }
  71723. else if (parsedData.physicsEngine === "oimo") {
  71724. physicsPlugin = new BABYLON.OimoJSPlugin();
  71725. }
  71726. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  71727. //else - default engine, which is currently oimo
  71728. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  71729. scene.enablePhysics(physicsGravity, physicsPlugin);
  71730. }
  71731. // Metadata
  71732. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  71733. scene.metadata = parsedData.metadata;
  71734. }
  71735. //collisions, if defined. otherwise, default is true
  71736. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  71737. scene.collisionsEnabled = parsedData.collisionsEnabled;
  71738. }
  71739. scene.workerCollisions = !!parsedData.workerCollisions;
  71740. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  71741. if (!container) {
  71742. return false;
  71743. }
  71744. if (parsedData.autoAnimate) {
  71745. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  71746. }
  71747. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  71748. scene.setActiveCameraByID(parsedData.activeCameraID);
  71749. }
  71750. // Environment texture
  71751. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  71752. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  71753. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  71754. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  71755. if (parsedData.environmentTextureRotationY) {
  71756. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  71757. }
  71758. scene.environmentTexture = hdrTexture;
  71759. }
  71760. else {
  71761. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  71762. if (parsedData.environmentTextureRotationY) {
  71763. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  71764. }
  71765. scene.environmentTexture = cubeTexture;
  71766. }
  71767. if (parsedData.createDefaultSkybox === true) {
  71768. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  71769. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  71770. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  71771. }
  71772. }
  71773. // Finish
  71774. return true;
  71775. }
  71776. catch (err) {
  71777. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  71778. if (onError) {
  71779. onError(msg, err);
  71780. }
  71781. else {
  71782. BABYLON.Tools.Log(msg);
  71783. throw err;
  71784. }
  71785. }
  71786. finally {
  71787. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  71788. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  71789. }
  71790. }
  71791. return false;
  71792. },
  71793. loadAssetContainer: function (scene, data, rootUrl, onError) {
  71794. var container = loadAssetContainer(scene, data, rootUrl, onError);
  71795. return container;
  71796. }
  71797. });
  71798. })(BABYLON || (BABYLON = {}));
  71799. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  71800. var BABYLON;
  71801. (function (BABYLON) {
  71802. var FilesInput = /** @class */ (function () {
  71803. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  71804. this.onProcessFileCallback = function () { return true; };
  71805. this._engine = engine;
  71806. this._currentScene = scene;
  71807. this._sceneLoadedCallback = sceneLoadedCallback;
  71808. this._progressCallback = progressCallback;
  71809. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  71810. this._textureLoadingCallback = textureLoadingCallback;
  71811. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  71812. this._onReloadCallback = onReloadCallback;
  71813. this._errorCallback = errorCallback;
  71814. }
  71815. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  71816. var _this = this;
  71817. if (elementToMonitor) {
  71818. this._elementToMonitor = elementToMonitor;
  71819. this._dragEnterHandler = function (e) { _this.drag(e); };
  71820. this._dragOverHandler = function (e) { _this.drag(e); };
  71821. this._dropHandler = function (e) { _this.drop(e); };
  71822. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  71823. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  71824. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  71825. }
  71826. };
  71827. FilesInput.prototype.dispose = function () {
  71828. if (!this._elementToMonitor) {
  71829. return;
  71830. }
  71831. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  71832. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  71833. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  71834. };
  71835. FilesInput.prototype.renderFunction = function () {
  71836. if (this._additionalRenderLoopLogicCallback) {
  71837. this._additionalRenderLoopLogicCallback();
  71838. }
  71839. if (this._currentScene) {
  71840. if (this._textureLoadingCallback) {
  71841. var remaining = this._currentScene.getWaitingItemsCount();
  71842. if (remaining > 0) {
  71843. this._textureLoadingCallback(remaining);
  71844. }
  71845. }
  71846. this._currentScene.render();
  71847. }
  71848. };
  71849. FilesInput.prototype.drag = function (e) {
  71850. e.stopPropagation();
  71851. e.preventDefault();
  71852. };
  71853. FilesInput.prototype.drop = function (eventDrop) {
  71854. eventDrop.stopPropagation();
  71855. eventDrop.preventDefault();
  71856. this.loadFiles(eventDrop);
  71857. };
  71858. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  71859. var _this = this;
  71860. var reader = folder.createReader();
  71861. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  71862. reader.readEntries(function (entries) {
  71863. remaining.count += entries.length;
  71864. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  71865. var entry = entries_1[_i];
  71866. if (entry.isFile) {
  71867. entry.file(function (file) {
  71868. file.correctName = relativePath + file.name;
  71869. files.push(file);
  71870. if (--remaining.count === 0) {
  71871. callback();
  71872. }
  71873. });
  71874. }
  71875. else if (entry.isDirectory) {
  71876. _this._traverseFolder(entry, files, remaining, callback);
  71877. }
  71878. }
  71879. if (--remaining.count) {
  71880. callback();
  71881. }
  71882. });
  71883. };
  71884. FilesInput.prototype._processFiles = function (files) {
  71885. for (var i = 0; i < files.length; i++) {
  71886. var name = files[i].correctName.toLowerCase();
  71887. var extension = name.split('.').pop();
  71888. if (!this.onProcessFileCallback(files[i], name, extension)) {
  71889. continue;
  71890. }
  71891. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  71892. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  71893. this._sceneFileToLoad = files[i];
  71894. }
  71895. else {
  71896. FilesInput.FilesToLoad[name] = files[i];
  71897. }
  71898. }
  71899. };
  71900. FilesInput.prototype.loadFiles = function (event) {
  71901. var _this = this;
  71902. // Handling data transfer via drag'n'drop
  71903. if (event && event.dataTransfer && event.dataTransfer.files) {
  71904. this._filesToLoad = event.dataTransfer.files;
  71905. }
  71906. // Handling files from input files
  71907. if (event && event.target && event.target.files) {
  71908. this._filesToLoad = event.target.files;
  71909. }
  71910. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  71911. return;
  71912. }
  71913. if (this._startingProcessingFilesCallback) {
  71914. this._startingProcessingFilesCallback(this._filesToLoad);
  71915. }
  71916. if (this._filesToLoad && this._filesToLoad.length > 0) {
  71917. var files_1 = new Array();
  71918. var folders = [];
  71919. var items = event.dataTransfer ? event.dataTransfer.items : null;
  71920. for (var i = 0; i < this._filesToLoad.length; i++) {
  71921. var fileToLoad = this._filesToLoad[i];
  71922. var name_1 = fileToLoad.name.toLowerCase();
  71923. var entry = void 0;
  71924. fileToLoad.correctName = name_1;
  71925. if (items) {
  71926. var item = items[i];
  71927. if (item.getAsEntry) {
  71928. entry = item.getAsEntry();
  71929. }
  71930. else if (item.webkitGetAsEntry) {
  71931. entry = item.webkitGetAsEntry();
  71932. }
  71933. }
  71934. if (!entry) {
  71935. files_1.push(fileToLoad);
  71936. }
  71937. else {
  71938. if (entry.isDirectory) {
  71939. folders.push(entry);
  71940. }
  71941. else {
  71942. files_1.push(fileToLoad);
  71943. }
  71944. }
  71945. }
  71946. if (folders.length === 0) {
  71947. this._processFiles(files_1);
  71948. this._processReload();
  71949. }
  71950. else {
  71951. var remaining = { count: folders.length };
  71952. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  71953. var folder = folders_1[_i];
  71954. this._traverseFolder(folder, files_1, remaining, function () {
  71955. _this._processFiles(files_1);
  71956. if (remaining.count === 0) {
  71957. _this._processReload();
  71958. }
  71959. });
  71960. }
  71961. }
  71962. }
  71963. };
  71964. FilesInput.prototype._processReload = function () {
  71965. if (this._onReloadCallback) {
  71966. this._onReloadCallback(this._sceneFileToLoad);
  71967. }
  71968. else {
  71969. this.reload();
  71970. }
  71971. };
  71972. FilesInput.prototype.reload = function () {
  71973. var _this = this;
  71974. // If a scene file has been provided
  71975. if (this._sceneFileToLoad) {
  71976. if (this._currentScene) {
  71977. if (BABYLON.Tools.errorsCount > 0) {
  71978. BABYLON.Tools.ClearLogCache();
  71979. }
  71980. this._engine.stopRenderLoop();
  71981. }
  71982. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  71983. if (_this._progressCallback) {
  71984. _this._progressCallback(progress);
  71985. }
  71986. }).then(function (scene) {
  71987. if (_this._currentScene) {
  71988. _this._currentScene.dispose();
  71989. }
  71990. _this._currentScene = scene;
  71991. if (_this._sceneLoadedCallback) {
  71992. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  71993. }
  71994. // Wait for textures and shaders to be ready
  71995. _this._currentScene.executeWhenReady(function () {
  71996. _this._engine.runRenderLoop(function () {
  71997. _this.renderFunction();
  71998. });
  71999. });
  72000. }).catch(function (error) {
  72001. if (_this._errorCallback) {
  72002. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  72003. }
  72004. });
  72005. }
  72006. else {
  72007. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  72008. }
  72009. };
  72010. FilesInput.FilesToLoad = {};
  72011. return FilesInput;
  72012. }());
  72013. BABYLON.FilesInput = FilesInput;
  72014. })(BABYLON || (BABYLON = {}));
  72015. //# sourceMappingURL=babylon.filesInput.js.map
  72016. var BABYLON;
  72017. (function (BABYLON) {
  72018. var Tags = /** @class */ (function () {
  72019. function Tags() {
  72020. }
  72021. Tags.EnableFor = function (obj) {
  72022. obj._tags = obj._tags || {};
  72023. obj.hasTags = function () {
  72024. return Tags.HasTags(obj);
  72025. };
  72026. obj.addTags = function (tagsString) {
  72027. return Tags.AddTagsTo(obj, tagsString);
  72028. };
  72029. obj.removeTags = function (tagsString) {
  72030. return Tags.RemoveTagsFrom(obj, tagsString);
  72031. };
  72032. obj.matchesTagsQuery = function (tagsQuery) {
  72033. return Tags.MatchesQuery(obj, tagsQuery);
  72034. };
  72035. };
  72036. Tags.DisableFor = function (obj) {
  72037. delete obj._tags;
  72038. delete obj.hasTags;
  72039. delete obj.addTags;
  72040. delete obj.removeTags;
  72041. delete obj.matchesTagsQuery;
  72042. };
  72043. Tags.HasTags = function (obj) {
  72044. if (!obj._tags) {
  72045. return false;
  72046. }
  72047. return !BABYLON.Tools.IsEmpty(obj._tags);
  72048. };
  72049. Tags.GetTags = function (obj, asString) {
  72050. if (asString === void 0) { asString = true; }
  72051. if (!obj._tags) {
  72052. return null;
  72053. }
  72054. if (asString) {
  72055. var tagsArray = [];
  72056. for (var tag in obj._tags) {
  72057. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  72058. tagsArray.push(tag);
  72059. }
  72060. }
  72061. return tagsArray.join(" ");
  72062. }
  72063. else {
  72064. return obj._tags;
  72065. }
  72066. };
  72067. // the tags 'true' and 'false' are reserved and cannot be used as tags
  72068. // a tag cannot start with '||', '&&', and '!'
  72069. // it cannot contain whitespaces
  72070. Tags.AddTagsTo = function (obj, tagsString) {
  72071. if (!tagsString) {
  72072. return;
  72073. }
  72074. if (typeof tagsString !== "string") {
  72075. return;
  72076. }
  72077. var tags = tagsString.split(" ");
  72078. tags.forEach(function (tag, index, array) {
  72079. Tags._AddTagTo(obj, tag);
  72080. });
  72081. };
  72082. Tags._AddTagTo = function (obj, tag) {
  72083. tag = tag.trim();
  72084. if (tag === "" || tag === "true" || tag === "false") {
  72085. return;
  72086. }
  72087. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  72088. return;
  72089. }
  72090. Tags.EnableFor(obj);
  72091. obj._tags[tag] = true;
  72092. };
  72093. Tags.RemoveTagsFrom = function (obj, tagsString) {
  72094. if (!Tags.HasTags(obj)) {
  72095. return;
  72096. }
  72097. var tags = tagsString.split(" ");
  72098. for (var t in tags) {
  72099. Tags._RemoveTagFrom(obj, tags[t]);
  72100. }
  72101. };
  72102. Tags._RemoveTagFrom = function (obj, tag) {
  72103. delete obj._tags[tag];
  72104. };
  72105. Tags.MatchesQuery = function (obj, tagsQuery) {
  72106. if (tagsQuery === undefined) {
  72107. return true;
  72108. }
  72109. if (tagsQuery === "") {
  72110. return Tags.HasTags(obj);
  72111. }
  72112. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  72113. };
  72114. return Tags;
  72115. }());
  72116. BABYLON.Tags = Tags;
  72117. })(BABYLON || (BABYLON = {}));
  72118. //# sourceMappingURL=babylon.tags.js.map
  72119. var BABYLON;
  72120. (function (BABYLON) {
  72121. /**
  72122. * Class used to evalaute queries containing `and` and `or` operators
  72123. */
  72124. var AndOrNotEvaluator = /** @class */ (function () {
  72125. function AndOrNotEvaluator() {
  72126. }
  72127. /**
  72128. * Evaluate a query
  72129. * @param query defines the query to evaluate
  72130. * @param evaluateCallback defines the callback used to filter result
  72131. * @returns true if the query matches
  72132. */
  72133. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  72134. if (!query.match(/\([^\(\)]*\)/g)) {
  72135. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  72136. }
  72137. else {
  72138. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  72139. // remove parenthesis
  72140. r = r.slice(1, r.length - 1);
  72141. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  72142. });
  72143. }
  72144. if (query === "true") {
  72145. return true;
  72146. }
  72147. if (query === "false") {
  72148. return false;
  72149. }
  72150. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  72151. };
  72152. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  72153. evaluateCallback = evaluateCallback || (function (r) {
  72154. return r === "true" ? true : false;
  72155. });
  72156. var result;
  72157. var or = parenthesisContent.split("||");
  72158. for (var i in or) {
  72159. if (or.hasOwnProperty(i)) {
  72160. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  72161. var and = ori.split("&&");
  72162. if (and.length > 1) {
  72163. for (var j = 0; j < and.length; ++j) {
  72164. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  72165. if (andj !== "true" && andj !== "false") {
  72166. if (andj[0] === "!") {
  72167. result = !evaluateCallback(andj.substring(1));
  72168. }
  72169. else {
  72170. result = evaluateCallback(andj);
  72171. }
  72172. }
  72173. else {
  72174. result = andj === "true" ? true : false;
  72175. }
  72176. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  72177. ori = "false";
  72178. break;
  72179. }
  72180. }
  72181. }
  72182. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  72183. result = true;
  72184. break;
  72185. }
  72186. // result equals false (or undefined)
  72187. if (ori !== "true" && ori !== "false") {
  72188. if (ori[0] === "!") {
  72189. result = !evaluateCallback(ori.substring(1));
  72190. }
  72191. else {
  72192. result = evaluateCallback(ori);
  72193. }
  72194. }
  72195. else {
  72196. result = ori === "true" ? true : false;
  72197. }
  72198. }
  72199. }
  72200. // the whole parenthesis scope is replaced by 'true' or 'false'
  72201. return result ? "true" : "false";
  72202. };
  72203. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  72204. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  72205. // remove whitespaces
  72206. r = r.replace(/[\s]/g, function () { return ""; });
  72207. return r.length % 2 ? "!" : "";
  72208. });
  72209. booleanString = booleanString.trim();
  72210. if (booleanString === "!true") {
  72211. booleanString = "false";
  72212. }
  72213. else if (booleanString === "!false") {
  72214. booleanString = "true";
  72215. }
  72216. return booleanString;
  72217. };
  72218. return AndOrNotEvaluator;
  72219. }());
  72220. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  72221. })(BABYLON || (BABYLON = {}));
  72222. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  72223. var BABYLON;
  72224. (function (BABYLON) {
  72225. /**
  72226. * Class used to enable access to IndexedDB
  72227. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  72228. */
  72229. var Database = /** @class */ (function () {
  72230. /**
  72231. * Creates a new Database
  72232. * @param urlToScene defines the url to load the scene
  72233. * @param callbackManifestChecked defines the callback to use when manifest is checked
  72234. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  72235. */
  72236. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  72237. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  72238. var _this = this;
  72239. // Handling various flavors of prefixed version of IndexedDB
  72240. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  72241. this.callbackManifestChecked = callbackManifestChecked;
  72242. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  72243. this.db = null;
  72244. this._enableSceneOffline = false;
  72245. this._enableTexturesOffline = false;
  72246. this.manifestVersionFound = 0;
  72247. this.mustUpdateRessources = false;
  72248. this.hasReachedQuota = false;
  72249. if (!Database.IDBStorageEnabled) {
  72250. this.callbackManifestChecked(true);
  72251. }
  72252. else {
  72253. if (disableManifestCheck) {
  72254. this._enableSceneOffline = true;
  72255. this._enableTexturesOffline = true;
  72256. this.manifestVersionFound = 1;
  72257. BABYLON.Tools.SetImmediate(function () {
  72258. _this.callbackManifestChecked(true);
  72259. });
  72260. }
  72261. else {
  72262. this._checkManifestFile();
  72263. }
  72264. }
  72265. }
  72266. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  72267. /**
  72268. * Gets a boolean indicating if scene must be saved in the database
  72269. */
  72270. get: function () {
  72271. return this._enableSceneOffline;
  72272. },
  72273. enumerable: true,
  72274. configurable: true
  72275. });
  72276. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  72277. /**
  72278. * Gets a boolean indicating if textures must be saved in the database
  72279. */
  72280. get: function () {
  72281. return this._enableTexturesOffline;
  72282. },
  72283. enumerable: true,
  72284. configurable: true
  72285. });
  72286. Database.prototype._checkManifestFile = function () {
  72287. var _this = this;
  72288. var noManifestFile = function () {
  72289. _this._enableSceneOffline = false;
  72290. _this._enableTexturesOffline = false;
  72291. _this.callbackManifestChecked(false);
  72292. };
  72293. var timeStampUsed = false;
  72294. var manifestURL = this.currentSceneUrl + ".manifest";
  72295. var xhr = new XMLHttpRequest();
  72296. if (navigator.onLine) {
  72297. // Adding a timestamp to by-pass browsers' cache
  72298. timeStampUsed = true;
  72299. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  72300. }
  72301. xhr.open("GET", manifestURL, true);
  72302. xhr.addEventListener("load", function () {
  72303. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  72304. try {
  72305. var manifestFile = JSON.parse(xhr.response);
  72306. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  72307. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  72308. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  72309. _this.manifestVersionFound = manifestFile.version;
  72310. }
  72311. if (_this.callbackManifestChecked) {
  72312. _this.callbackManifestChecked(true);
  72313. }
  72314. }
  72315. catch (ex) {
  72316. noManifestFile();
  72317. }
  72318. }
  72319. else {
  72320. noManifestFile();
  72321. }
  72322. }, false);
  72323. xhr.addEventListener("error", function (event) {
  72324. if (timeStampUsed) {
  72325. timeStampUsed = false;
  72326. // Let's retry without the timeStamp
  72327. // It could fail when coupled with HTML5 Offline API
  72328. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  72329. xhr.open("GET", retryManifestURL, true);
  72330. xhr.send();
  72331. }
  72332. else {
  72333. noManifestFile();
  72334. }
  72335. }, false);
  72336. try {
  72337. xhr.send();
  72338. }
  72339. catch (ex) {
  72340. BABYLON.Tools.Error("Error on XHR send request.");
  72341. this.callbackManifestChecked(false);
  72342. }
  72343. };
  72344. /**
  72345. * Open the database and make it available
  72346. * @param successCallback defines the callback to call on success
  72347. * @param errorCallback defines the callback to call on error
  72348. */
  72349. Database.prototype.openAsync = function (successCallback, errorCallback) {
  72350. var _this = this;
  72351. var handleError = function () {
  72352. _this.isSupported = false;
  72353. if (errorCallback)
  72354. errorCallback();
  72355. };
  72356. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  72357. // Your browser doesn't support IndexedDB
  72358. this.isSupported = false;
  72359. if (errorCallback)
  72360. errorCallback();
  72361. }
  72362. else {
  72363. // If the DB hasn't been opened or created yet
  72364. if (!this.db) {
  72365. this.hasReachedQuota = false;
  72366. this.isSupported = true;
  72367. var request = this.idbFactory.open("babylonjs", 1);
  72368. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  72369. request.onerror = function (event) {
  72370. handleError();
  72371. };
  72372. // executes when a version change transaction cannot complete due to other active transactions
  72373. request.onblocked = function (event) {
  72374. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  72375. handleError();
  72376. };
  72377. // DB has been opened successfully
  72378. request.onsuccess = function (event) {
  72379. _this.db = request.result;
  72380. successCallback();
  72381. };
  72382. // Initialization of the DB. Creating Scenes & Textures stores
  72383. request.onupgradeneeded = function (event) {
  72384. _this.db = (event.target).result;
  72385. if (_this.db) {
  72386. try {
  72387. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  72388. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  72389. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  72390. }
  72391. catch (ex) {
  72392. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  72393. handleError();
  72394. }
  72395. }
  72396. };
  72397. }
  72398. // DB has already been created and opened
  72399. else {
  72400. if (successCallback)
  72401. successCallback();
  72402. }
  72403. }
  72404. };
  72405. /**
  72406. * Loads an image from the database
  72407. * @param url defines the url to load from
  72408. * @param image defines the target DOM image
  72409. */
  72410. Database.prototype.loadImageFromDB = function (url, image) {
  72411. var _this = this;
  72412. var completeURL = Database._ReturnFullUrlLocation(url);
  72413. var saveAndLoadImage = function () {
  72414. if (!_this.hasReachedQuota && _this.db !== null) {
  72415. // the texture is not yet in the DB, let's try to save it
  72416. _this._saveImageIntoDBAsync(completeURL, image);
  72417. }
  72418. // If the texture is not in the DB and we've reached the DB quota limit
  72419. // let's load it directly from the web
  72420. else {
  72421. image.src = url;
  72422. }
  72423. };
  72424. if (!this.mustUpdateRessources) {
  72425. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  72426. }
  72427. // First time we're download the images or update requested in the manifest file by a version change
  72428. else {
  72429. saveAndLoadImage();
  72430. }
  72431. };
  72432. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  72433. if (this.isSupported && this.db !== null) {
  72434. var texture;
  72435. var transaction = this.db.transaction(["textures"]);
  72436. transaction.onabort = function (event) {
  72437. image.src = url;
  72438. };
  72439. transaction.oncomplete = function (event) {
  72440. var blobTextureURL;
  72441. if (texture) {
  72442. var URL = window.URL || window.webkitURL;
  72443. blobTextureURL = URL.createObjectURL(texture.data);
  72444. image.onerror = function () {
  72445. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  72446. image.src = url;
  72447. };
  72448. image.src = blobTextureURL;
  72449. }
  72450. else {
  72451. notInDBCallback();
  72452. }
  72453. };
  72454. var getRequest = transaction.objectStore("textures").get(url);
  72455. getRequest.onsuccess = function (event) {
  72456. texture = (event.target).result;
  72457. };
  72458. getRequest.onerror = function (event) {
  72459. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  72460. image.src = url;
  72461. };
  72462. }
  72463. else {
  72464. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72465. image.src = url;
  72466. }
  72467. };
  72468. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  72469. var _this = this;
  72470. if (this.isSupported) {
  72471. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  72472. var generateBlobUrl = function () {
  72473. var blobTextureURL;
  72474. if (blob) {
  72475. var URL = window.URL || window.webkitURL;
  72476. try {
  72477. blobTextureURL = URL.createObjectURL(blob);
  72478. }
  72479. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  72480. catch (ex) {
  72481. blobTextureURL = URL.createObjectURL(blob);
  72482. }
  72483. }
  72484. if (blobTextureURL) {
  72485. image.src = blobTextureURL;
  72486. }
  72487. };
  72488. if (Database.IsUASupportingBlobStorage) { // Create XHR
  72489. var xhr = new XMLHttpRequest(), blob;
  72490. xhr.open("GET", url, true);
  72491. xhr.responseType = "blob";
  72492. xhr.addEventListener("load", function () {
  72493. if (xhr.status === 200 && _this.db) {
  72494. // Blob as response (XHR2)
  72495. blob = xhr.response;
  72496. var transaction = _this.db.transaction(["textures"], "readwrite");
  72497. // the transaction could abort because of a QuotaExceededError error
  72498. transaction.onabort = function (event) {
  72499. try {
  72500. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  72501. var srcElement = (event.srcElement || event.target);
  72502. var error = srcElement.error;
  72503. if (error && error.name === "QuotaExceededError") {
  72504. _this.hasReachedQuota = true;
  72505. }
  72506. }
  72507. catch (ex) { }
  72508. generateBlobUrl();
  72509. };
  72510. transaction.oncomplete = function (event) {
  72511. generateBlobUrl();
  72512. };
  72513. var newTexture = { textureUrl: url, data: blob };
  72514. try {
  72515. // Put the blob into the dabase
  72516. var addRequest = transaction.objectStore("textures").put(newTexture);
  72517. addRequest.onsuccess = function (event) {
  72518. };
  72519. addRequest.onerror = function (event) {
  72520. generateBlobUrl();
  72521. };
  72522. }
  72523. catch (ex) {
  72524. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  72525. if (ex.code === 25) {
  72526. Database.IsUASupportingBlobStorage = false;
  72527. }
  72528. image.src = url;
  72529. }
  72530. }
  72531. else {
  72532. image.src = url;
  72533. }
  72534. }, false);
  72535. xhr.addEventListener("error", function (event) {
  72536. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  72537. image.src = url;
  72538. }, false);
  72539. xhr.send();
  72540. }
  72541. else {
  72542. image.src = url;
  72543. }
  72544. }
  72545. else {
  72546. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72547. image.src = url;
  72548. }
  72549. };
  72550. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  72551. var _this = this;
  72552. var updateVersion = function () {
  72553. // the version is not yet in the DB or we need to update it
  72554. _this._saveVersionIntoDBAsync(url, versionLoaded);
  72555. };
  72556. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  72557. };
  72558. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  72559. var _this = this;
  72560. if (this.isSupported && this.db) {
  72561. var version;
  72562. try {
  72563. var transaction = this.db.transaction(["versions"]);
  72564. transaction.oncomplete = function (event) {
  72565. if (version) {
  72566. // If the version in the JSON file is different from the version in DB
  72567. if (_this.manifestVersionFound !== version.data) {
  72568. _this.mustUpdateRessources = true;
  72569. updateInDBCallback();
  72570. }
  72571. else {
  72572. callback(version.data);
  72573. }
  72574. }
  72575. // version was not found in DB
  72576. else {
  72577. _this.mustUpdateRessources = true;
  72578. updateInDBCallback();
  72579. }
  72580. };
  72581. transaction.onabort = function (event) {
  72582. callback(-1);
  72583. };
  72584. var getRequest = transaction.objectStore("versions").get(url);
  72585. getRequest.onsuccess = function (event) {
  72586. version = (event.target).result;
  72587. };
  72588. getRequest.onerror = function (event) {
  72589. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  72590. callback(-1);
  72591. };
  72592. }
  72593. catch (ex) {
  72594. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  72595. callback(-1);
  72596. }
  72597. }
  72598. else {
  72599. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72600. callback(-1);
  72601. }
  72602. };
  72603. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  72604. var _this = this;
  72605. if (this.isSupported && !this.hasReachedQuota && this.db) {
  72606. try {
  72607. // Open a transaction to the database
  72608. var transaction = this.db.transaction(["versions"], "readwrite");
  72609. // the transaction could abort because of a QuotaExceededError error
  72610. transaction.onabort = function (event) {
  72611. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  72612. var error = event.srcElement['error'];
  72613. if (error && error.name === "QuotaExceededError") {
  72614. _this.hasReachedQuota = true;
  72615. }
  72616. }
  72617. catch (ex) { }
  72618. callback(-1);
  72619. };
  72620. transaction.oncomplete = function (event) {
  72621. callback(_this.manifestVersionFound);
  72622. };
  72623. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  72624. // Put the scene into the database
  72625. var addRequest = transaction.objectStore("versions").put(newVersion);
  72626. addRequest.onsuccess = function (event) {
  72627. };
  72628. addRequest.onerror = function (event) {
  72629. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  72630. };
  72631. }
  72632. catch (ex) {
  72633. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  72634. callback(-1);
  72635. }
  72636. }
  72637. else {
  72638. callback(-1);
  72639. }
  72640. };
  72641. /**
  72642. * Loads a file from database
  72643. * @param url defines the URL to load from
  72644. * @param sceneLoaded defines a callback to call on success
  72645. * @param progressCallBack defines a callback to call when progress changed
  72646. * @param errorCallback defines a callback to call on error
  72647. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  72648. */
  72649. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  72650. var _this = this;
  72651. var completeUrl = Database._ReturnFullUrlLocation(url);
  72652. var saveAndLoadFile = function () {
  72653. // the scene is not yet in the DB, let's try to save it
  72654. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  72655. };
  72656. this._checkVersionFromDB(completeUrl, function (version) {
  72657. if (version !== -1) {
  72658. if (!_this.mustUpdateRessources) {
  72659. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  72660. }
  72661. else {
  72662. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  72663. }
  72664. }
  72665. else {
  72666. if (errorCallback) {
  72667. errorCallback();
  72668. }
  72669. }
  72670. });
  72671. };
  72672. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  72673. if (this.isSupported && this.db) {
  72674. var targetStore;
  72675. if (url.indexOf(".babylon") !== -1) {
  72676. targetStore = "scenes";
  72677. }
  72678. else {
  72679. targetStore = "textures";
  72680. }
  72681. var file;
  72682. var transaction = this.db.transaction([targetStore]);
  72683. transaction.oncomplete = function (event) {
  72684. if (file) {
  72685. callback(file.data);
  72686. }
  72687. // file was not found in DB
  72688. else {
  72689. notInDBCallback();
  72690. }
  72691. };
  72692. transaction.onabort = function (event) {
  72693. notInDBCallback();
  72694. };
  72695. var getRequest = transaction.objectStore(targetStore).get(url);
  72696. getRequest.onsuccess = function (event) {
  72697. file = (event.target).result;
  72698. };
  72699. getRequest.onerror = function (event) {
  72700. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  72701. notInDBCallback();
  72702. };
  72703. }
  72704. else {
  72705. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72706. callback();
  72707. }
  72708. };
  72709. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  72710. var _this = this;
  72711. if (this.isSupported) {
  72712. var targetStore;
  72713. if (url.indexOf(".babylon") !== -1) {
  72714. targetStore = "scenes";
  72715. }
  72716. else {
  72717. targetStore = "textures";
  72718. }
  72719. // Create XHR
  72720. var xhr = new XMLHttpRequest();
  72721. var fileData;
  72722. xhr.open("GET", url + "?" + Date.now(), true);
  72723. if (useArrayBuffer) {
  72724. xhr.responseType = "arraybuffer";
  72725. }
  72726. if (progressCallback) {
  72727. xhr.onprogress = progressCallback;
  72728. }
  72729. xhr.addEventListener("load", function () {
  72730. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  72731. // Blob as response (XHR2)
  72732. //fileData = xhr.responseText;
  72733. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  72734. if (!_this.hasReachedQuota && _this.db) {
  72735. // Open a transaction to the database
  72736. var transaction = _this.db.transaction([targetStore], "readwrite");
  72737. // the transaction could abort because of a QuotaExceededError error
  72738. transaction.onabort = function (event) {
  72739. try {
  72740. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  72741. var error = event.srcElement['error'];
  72742. if (error && error.name === "QuotaExceededError") {
  72743. _this.hasReachedQuota = true;
  72744. }
  72745. }
  72746. catch (ex) { }
  72747. callback(fileData);
  72748. };
  72749. transaction.oncomplete = function (event) {
  72750. callback(fileData);
  72751. };
  72752. var newFile;
  72753. if (targetStore === "scenes") {
  72754. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  72755. }
  72756. else {
  72757. newFile = { textureUrl: url, data: fileData };
  72758. }
  72759. try {
  72760. // Put the scene into the database
  72761. var addRequest = transaction.objectStore(targetStore).put(newFile);
  72762. addRequest.onsuccess = function (event) {
  72763. };
  72764. addRequest.onerror = function (event) {
  72765. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  72766. };
  72767. }
  72768. catch (ex) {
  72769. callback(fileData);
  72770. }
  72771. }
  72772. else {
  72773. callback(fileData);
  72774. }
  72775. }
  72776. else {
  72777. if (xhr.status >= 400 && errorCallback) {
  72778. errorCallback(xhr);
  72779. }
  72780. else {
  72781. callback();
  72782. }
  72783. }
  72784. }, false);
  72785. xhr.addEventListener("error", function (event) {
  72786. BABYLON.Tools.Error("error on XHR request.");
  72787. callback();
  72788. }, false);
  72789. xhr.send();
  72790. }
  72791. else {
  72792. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72793. callback();
  72794. }
  72795. };
  72796. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  72797. Database.IsUASupportingBlobStorage = true;
  72798. /** Gets a boolean indicating if Database storate is enabled */
  72799. Database.IDBStorageEnabled = true;
  72800. Database._ParseURL = function (url) {
  72801. var a = document.createElement('a');
  72802. a.href = url;
  72803. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  72804. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  72805. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  72806. return absLocation;
  72807. };
  72808. Database._ReturnFullUrlLocation = function (url) {
  72809. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  72810. return (Database._ParseURL(window.location.href) + url);
  72811. }
  72812. else {
  72813. return url;
  72814. }
  72815. };
  72816. return Database;
  72817. }());
  72818. BABYLON.Database = Database;
  72819. })(BABYLON || (BABYLON = {}));
  72820. //# sourceMappingURL=babylon.database.js.map
  72821. var BABYLON;
  72822. (function (BABYLON) {
  72823. var FresnelParameters = /** @class */ (function () {
  72824. function FresnelParameters() {
  72825. this._isEnabled = true;
  72826. this.leftColor = BABYLON.Color3.White();
  72827. this.rightColor = BABYLON.Color3.Black();
  72828. this.bias = 0;
  72829. this.power = 1;
  72830. }
  72831. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  72832. get: function () {
  72833. return this._isEnabled;
  72834. },
  72835. set: function (value) {
  72836. if (this._isEnabled === value) {
  72837. return;
  72838. }
  72839. this._isEnabled = value;
  72840. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  72841. },
  72842. enumerable: true,
  72843. configurable: true
  72844. });
  72845. FresnelParameters.prototype.clone = function () {
  72846. var newFresnelParameters = new FresnelParameters();
  72847. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  72848. return newFresnelParameters;
  72849. };
  72850. FresnelParameters.prototype.serialize = function () {
  72851. var serializationObject = {};
  72852. serializationObject.isEnabled = this.isEnabled;
  72853. serializationObject.leftColor = this.leftColor.asArray();
  72854. serializationObject.rightColor = this.rightColor.asArray();
  72855. serializationObject.bias = this.bias;
  72856. serializationObject.power = this.power;
  72857. return serializationObject;
  72858. };
  72859. FresnelParameters.Parse = function (parsedFresnelParameters) {
  72860. var fresnelParameters = new FresnelParameters();
  72861. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  72862. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  72863. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  72864. fresnelParameters.bias = parsedFresnelParameters.bias;
  72865. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  72866. return fresnelParameters;
  72867. };
  72868. return FresnelParameters;
  72869. }());
  72870. BABYLON.FresnelParameters = FresnelParameters;
  72871. })(BABYLON || (BABYLON = {}));
  72872. //# sourceMappingURL=babylon.fresnelParameters.js.map
  72873. var BABYLON;
  72874. (function (BABYLON) {
  72875. var MultiMaterial = /** @class */ (function (_super) {
  72876. __extends(MultiMaterial, _super);
  72877. function MultiMaterial(name, scene) {
  72878. var _this = _super.call(this, name, scene, true) || this;
  72879. scene.multiMaterials.push(_this);
  72880. _this.subMaterials = new Array();
  72881. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  72882. return _this;
  72883. }
  72884. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  72885. get: function () {
  72886. return this._subMaterials;
  72887. },
  72888. set: function (value) {
  72889. this._subMaterials = value;
  72890. this._hookArray(value);
  72891. },
  72892. enumerable: true,
  72893. configurable: true
  72894. });
  72895. MultiMaterial.prototype._hookArray = function (array) {
  72896. var _this = this;
  72897. var oldPush = array.push;
  72898. array.push = function () {
  72899. var items = [];
  72900. for (var _i = 0; _i < arguments.length; _i++) {
  72901. items[_i] = arguments[_i];
  72902. }
  72903. var result = oldPush.apply(array, items);
  72904. _this._markAllSubMeshesAsTexturesDirty();
  72905. return result;
  72906. };
  72907. var oldSplice = array.splice;
  72908. array.splice = function (index, deleteCount) {
  72909. var deleted = oldSplice.apply(array, [index, deleteCount]);
  72910. _this._markAllSubMeshesAsTexturesDirty();
  72911. return deleted;
  72912. };
  72913. };
  72914. // Properties
  72915. MultiMaterial.prototype.getSubMaterial = function (index) {
  72916. if (index < 0 || index >= this.subMaterials.length) {
  72917. return this.getScene().defaultMaterial;
  72918. }
  72919. return this.subMaterials[index];
  72920. };
  72921. MultiMaterial.prototype.getActiveTextures = function () {
  72922. var _a;
  72923. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  72924. if (subMaterial) {
  72925. return subMaterial.getActiveTextures();
  72926. }
  72927. else {
  72928. return [];
  72929. }
  72930. }));
  72931. };
  72932. // Methods
  72933. MultiMaterial.prototype.getClassName = function () {
  72934. return "MultiMaterial";
  72935. };
  72936. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  72937. for (var index = 0; index < this.subMaterials.length; index++) {
  72938. var subMaterial = this.subMaterials[index];
  72939. if (subMaterial) {
  72940. if (subMaterial.storeEffectOnSubMeshes) {
  72941. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  72942. return false;
  72943. }
  72944. continue;
  72945. }
  72946. if (!subMaterial.isReady(mesh)) {
  72947. return false;
  72948. }
  72949. }
  72950. }
  72951. return true;
  72952. };
  72953. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  72954. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  72955. for (var index = 0; index < this.subMaterials.length; index++) {
  72956. var subMaterial = null;
  72957. var current = this.subMaterials[index];
  72958. if (cloneChildren && current) {
  72959. subMaterial = current.clone(name + "-" + current.name);
  72960. }
  72961. else {
  72962. subMaterial = this.subMaterials[index];
  72963. }
  72964. newMultiMaterial.subMaterials.push(subMaterial);
  72965. }
  72966. return newMultiMaterial;
  72967. };
  72968. MultiMaterial.prototype.serialize = function () {
  72969. var serializationObject = {};
  72970. serializationObject.name = this.name;
  72971. serializationObject.id = this.id;
  72972. if (BABYLON.Tags) {
  72973. serializationObject.tags = BABYLON.Tags.GetTags(this);
  72974. }
  72975. serializationObject.materials = [];
  72976. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  72977. var subMat = this.subMaterials[matIndex];
  72978. if (subMat) {
  72979. serializationObject.materials.push(subMat.id);
  72980. }
  72981. else {
  72982. serializationObject.materials.push(null);
  72983. }
  72984. }
  72985. return serializationObject;
  72986. };
  72987. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  72988. var scene = this.getScene();
  72989. if (!scene) {
  72990. return;
  72991. }
  72992. var index = scene.multiMaterials.indexOf(this);
  72993. if (index >= 0) {
  72994. scene.multiMaterials.splice(index, 1);
  72995. }
  72996. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  72997. };
  72998. return MultiMaterial;
  72999. }(BABYLON.Material));
  73000. BABYLON.MultiMaterial = MultiMaterial;
  73001. })(BABYLON || (BABYLON = {}));
  73002. //# sourceMappingURL=babylon.multiMaterial.js.map
  73003. var BABYLON;
  73004. (function (BABYLON) {
  73005. var FreeCameraTouchInput = /** @class */ (function () {
  73006. function FreeCameraTouchInput() {
  73007. this._offsetX = null;
  73008. this._offsetY = null;
  73009. this._pointerPressed = new Array();
  73010. this.touchAngularSensibility = 200000.0;
  73011. this.touchMoveSensibility = 250.0;
  73012. }
  73013. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  73014. var _this = this;
  73015. var previousPosition = null;
  73016. if (this._pointerInput === undefined) {
  73017. this._onLostFocus = function (evt) {
  73018. _this._offsetX = null;
  73019. _this._offsetY = null;
  73020. };
  73021. this._pointerInput = function (p, s) {
  73022. var evt = p.event;
  73023. if (evt.pointerType === "mouse") {
  73024. return;
  73025. }
  73026. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  73027. if (!noPreventDefault) {
  73028. evt.preventDefault();
  73029. }
  73030. _this._pointerPressed.push(evt.pointerId);
  73031. if (_this._pointerPressed.length !== 1) {
  73032. return;
  73033. }
  73034. previousPosition = {
  73035. x: evt.clientX,
  73036. y: evt.clientY
  73037. };
  73038. }
  73039. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  73040. if (!noPreventDefault) {
  73041. evt.preventDefault();
  73042. }
  73043. var index = _this._pointerPressed.indexOf(evt.pointerId);
  73044. if (index === -1) {
  73045. return;
  73046. }
  73047. _this._pointerPressed.splice(index, 1);
  73048. if (index != 0) {
  73049. return;
  73050. }
  73051. previousPosition = null;
  73052. _this._offsetX = null;
  73053. _this._offsetY = null;
  73054. }
  73055. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  73056. if (!noPreventDefault) {
  73057. evt.preventDefault();
  73058. }
  73059. if (!previousPosition) {
  73060. return;
  73061. }
  73062. var index = _this._pointerPressed.indexOf(evt.pointerId);
  73063. if (index != 0) {
  73064. return;
  73065. }
  73066. _this._offsetX = evt.clientX - previousPosition.x;
  73067. _this._offsetY = -(evt.clientY - previousPosition.y);
  73068. }
  73069. };
  73070. }
  73071. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  73072. if (this._onLostFocus) {
  73073. element.addEventListener("blur", this._onLostFocus);
  73074. }
  73075. };
  73076. FreeCameraTouchInput.prototype.detachControl = function (element) {
  73077. if (this._pointerInput && element) {
  73078. if (this._observer) {
  73079. this.camera.getScene().onPointerObservable.remove(this._observer);
  73080. this._observer = null;
  73081. }
  73082. if (this._onLostFocus) {
  73083. element.removeEventListener("blur", this._onLostFocus);
  73084. this._onLostFocus = null;
  73085. }
  73086. this._pointerPressed = [];
  73087. this._offsetX = null;
  73088. this._offsetY = null;
  73089. }
  73090. };
  73091. FreeCameraTouchInput.prototype.checkInputs = function () {
  73092. if (this._offsetX && this._offsetY) {
  73093. var camera = this.camera;
  73094. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  73095. if (this._pointerPressed.length > 1) {
  73096. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  73097. }
  73098. else {
  73099. var speed = camera._computeLocalCameraSpeed();
  73100. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  73101. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  73102. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  73103. }
  73104. }
  73105. };
  73106. FreeCameraTouchInput.prototype.getClassName = function () {
  73107. return "FreeCameraTouchInput";
  73108. };
  73109. FreeCameraTouchInput.prototype.getSimpleName = function () {
  73110. return "touch";
  73111. };
  73112. __decorate([
  73113. BABYLON.serialize()
  73114. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  73115. __decorate([
  73116. BABYLON.serialize()
  73117. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  73118. return FreeCameraTouchInput;
  73119. }());
  73120. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  73121. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  73122. })(BABYLON || (BABYLON = {}));
  73123. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  73124. var BABYLON;
  73125. (function (BABYLON) {
  73126. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  73127. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  73128. });
  73129. // We're mainly based on the logic defined into the FreeCamera code
  73130. var TouchCamera = /** @class */ (function (_super) {
  73131. __extends(TouchCamera, _super);
  73132. //-- end properties for backward compatibility for inputs
  73133. function TouchCamera(name, position, scene) {
  73134. var _this = _super.call(this, name, position, scene) || this;
  73135. _this.inputs.addTouch();
  73136. _this._setupInputs();
  73137. return _this;
  73138. }
  73139. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  73140. //-- Begin properties for backward compatibility for inputs
  73141. get: function () {
  73142. var touch = this.inputs.attached["touch"];
  73143. if (touch)
  73144. return touch.touchAngularSensibility;
  73145. return 0;
  73146. },
  73147. set: function (value) {
  73148. var touch = this.inputs.attached["touch"];
  73149. if (touch)
  73150. touch.touchAngularSensibility = value;
  73151. },
  73152. enumerable: true,
  73153. configurable: true
  73154. });
  73155. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  73156. get: function () {
  73157. var touch = this.inputs.attached["touch"];
  73158. if (touch)
  73159. return touch.touchMoveSensibility;
  73160. return 0;
  73161. },
  73162. set: function (value) {
  73163. var touch = this.inputs.attached["touch"];
  73164. if (touch)
  73165. touch.touchMoveSensibility = value;
  73166. },
  73167. enumerable: true,
  73168. configurable: true
  73169. });
  73170. TouchCamera.prototype.getClassName = function () {
  73171. return "TouchCamera";
  73172. };
  73173. /** @hidden */
  73174. TouchCamera.prototype._setupInputs = function () {
  73175. var mouse = this.inputs.attached["mouse"];
  73176. if (mouse) {
  73177. mouse.touchEnabled = false;
  73178. }
  73179. };
  73180. return TouchCamera;
  73181. }(BABYLON.FreeCamera));
  73182. BABYLON.TouchCamera = TouchCamera;
  73183. })(BABYLON || (BABYLON = {}));
  73184. //# sourceMappingURL=babylon.touchCamera.js.map
  73185. var BABYLON;
  73186. (function (BABYLON) {
  73187. var ProceduralTexture = /** @class */ (function (_super) {
  73188. __extends(ProceduralTexture, _super);
  73189. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  73190. if (fallbackTexture === void 0) { fallbackTexture = null; }
  73191. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73192. if (isCube === void 0) { isCube = false; }
  73193. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  73194. _this.isCube = isCube;
  73195. _this.isEnabled = true;
  73196. _this._currentRefreshId = -1;
  73197. _this._refreshRate = 1;
  73198. _this._vertexBuffers = {};
  73199. _this._uniforms = new Array();
  73200. _this._samplers = new Array();
  73201. /** @hidden */
  73202. _this._textures = {};
  73203. _this._floats = {};
  73204. _this._ints = {};
  73205. _this._floatsArrays = {};
  73206. _this._colors3 = {};
  73207. _this._colors4 = {};
  73208. _this._vectors2 = {};
  73209. _this._vectors3 = {};
  73210. _this._matrices = {};
  73211. _this._fallbackTextureUsed = false;
  73212. _this._cachedDefines = "";
  73213. scene = _this.getScene();
  73214. scene.proceduralTextures.push(_this);
  73215. _this._engine = scene.getEngine();
  73216. _this.name = name;
  73217. _this.isRenderTarget = true;
  73218. _this._size = size;
  73219. _this._generateMipMaps = generateMipMaps;
  73220. _this.setFragment(fragment);
  73221. _this._fallbackTexture = fallbackTexture;
  73222. if (isCube) {
  73223. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  73224. _this.setFloat("face", 0);
  73225. }
  73226. else {
  73227. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  73228. }
  73229. // VBO
  73230. var vertices = [];
  73231. vertices.push(1, 1);
  73232. vertices.push(-1, 1);
  73233. vertices.push(-1, -1);
  73234. vertices.push(1, -1);
  73235. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73236. _this._createIndexBuffer();
  73237. return _this;
  73238. }
  73239. ProceduralTexture.prototype._createIndexBuffer = function () {
  73240. var engine = this._engine;
  73241. // Indices
  73242. var indices = [];
  73243. indices.push(0);
  73244. indices.push(1);
  73245. indices.push(2);
  73246. indices.push(0);
  73247. indices.push(2);
  73248. indices.push(3);
  73249. this._indexBuffer = engine.createIndexBuffer(indices);
  73250. };
  73251. /** @hidden */
  73252. ProceduralTexture.prototype._rebuild = function () {
  73253. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73254. if (vb) {
  73255. vb._rebuild();
  73256. }
  73257. this._createIndexBuffer();
  73258. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  73259. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  73260. }
  73261. };
  73262. ProceduralTexture.prototype.reset = function () {
  73263. if (this._effect === undefined) {
  73264. return;
  73265. }
  73266. var engine = this._engine;
  73267. engine._releaseEffect(this._effect);
  73268. };
  73269. ProceduralTexture.prototype._getDefines = function () {
  73270. return "";
  73271. };
  73272. ProceduralTexture.prototype.isReady = function () {
  73273. var _this = this;
  73274. var engine = this._engine;
  73275. var shaders;
  73276. if (!this._fragment) {
  73277. return false;
  73278. }
  73279. if (this._fallbackTextureUsed) {
  73280. return true;
  73281. }
  73282. var defines = this._getDefines();
  73283. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  73284. return true;
  73285. }
  73286. if (this._fragment.fragmentElement !== undefined) {
  73287. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  73288. }
  73289. else {
  73290. shaders = { vertex: "procedural", fragment: this._fragment };
  73291. }
  73292. this._cachedDefines = defines;
  73293. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  73294. _this.releaseInternalTexture();
  73295. if (_this._fallbackTexture) {
  73296. _this._texture = _this._fallbackTexture._texture;
  73297. if (_this._texture) {
  73298. _this._texture.incrementReferences();
  73299. }
  73300. }
  73301. _this._fallbackTextureUsed = true;
  73302. });
  73303. return this._effect.isReady();
  73304. };
  73305. ProceduralTexture.prototype.resetRefreshCounter = function () {
  73306. this._currentRefreshId = -1;
  73307. };
  73308. ProceduralTexture.prototype.setFragment = function (fragment) {
  73309. this._fragment = fragment;
  73310. };
  73311. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  73312. get: function () {
  73313. return this._refreshRate;
  73314. },
  73315. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  73316. set: function (value) {
  73317. this._refreshRate = value;
  73318. this.resetRefreshCounter();
  73319. },
  73320. enumerable: true,
  73321. configurable: true
  73322. });
  73323. /** @hidden */
  73324. ProceduralTexture.prototype._shouldRender = function () {
  73325. if (!this.isEnabled || !this.isReady() || !this._texture) {
  73326. return false;
  73327. }
  73328. if (this._fallbackTextureUsed) {
  73329. return false;
  73330. }
  73331. if (this._currentRefreshId === -1) { // At least render once
  73332. this._currentRefreshId = 1;
  73333. return true;
  73334. }
  73335. if (this.refreshRate === this._currentRefreshId) {
  73336. this._currentRefreshId = 1;
  73337. return true;
  73338. }
  73339. this._currentRefreshId++;
  73340. return false;
  73341. };
  73342. ProceduralTexture.prototype.getRenderSize = function () {
  73343. return this._size;
  73344. };
  73345. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  73346. if (this._fallbackTextureUsed) {
  73347. return;
  73348. }
  73349. this.releaseInternalTexture();
  73350. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  73351. // Update properties
  73352. this._size = size;
  73353. this._generateMipMaps = generateMipMaps;
  73354. };
  73355. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  73356. if (this._uniforms.indexOf(uniformName) === -1) {
  73357. this._uniforms.push(uniformName);
  73358. }
  73359. };
  73360. ProceduralTexture.prototype.setTexture = function (name, texture) {
  73361. if (this._samplers.indexOf(name) === -1) {
  73362. this._samplers.push(name);
  73363. }
  73364. this._textures[name] = texture;
  73365. return this;
  73366. };
  73367. ProceduralTexture.prototype.setFloat = function (name, value) {
  73368. this._checkUniform(name);
  73369. this._floats[name] = value;
  73370. return this;
  73371. };
  73372. /**
  73373. * Set the value of an uniform to an integer value
  73374. * @param name defines the name of the uniform
  73375. * @param value defines the value to set
  73376. * @returns the current procedural texture
  73377. */
  73378. ProceduralTexture.prototype.setInt = function (name, value) {
  73379. this._checkUniform(name);
  73380. this._ints[name] = value;
  73381. return this;
  73382. };
  73383. ProceduralTexture.prototype.setFloats = function (name, value) {
  73384. this._checkUniform(name);
  73385. this._floatsArrays[name] = value;
  73386. return this;
  73387. };
  73388. ProceduralTexture.prototype.setColor3 = function (name, value) {
  73389. this._checkUniform(name);
  73390. this._colors3[name] = value;
  73391. return this;
  73392. };
  73393. ProceduralTexture.prototype.setColor4 = function (name, value) {
  73394. this._checkUniform(name);
  73395. this._colors4[name] = value;
  73396. return this;
  73397. };
  73398. ProceduralTexture.prototype.setVector2 = function (name, value) {
  73399. this._checkUniform(name);
  73400. this._vectors2[name] = value;
  73401. return this;
  73402. };
  73403. ProceduralTexture.prototype.setVector3 = function (name, value) {
  73404. this._checkUniform(name);
  73405. this._vectors3[name] = value;
  73406. return this;
  73407. };
  73408. ProceduralTexture.prototype.setMatrix = function (name, value) {
  73409. this._checkUniform(name);
  73410. this._matrices[name] = value;
  73411. return this;
  73412. };
  73413. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  73414. var scene = this.getScene();
  73415. if (!scene) {
  73416. return;
  73417. }
  73418. var engine = this._engine;
  73419. // Render
  73420. engine.enableEffect(this._effect);
  73421. engine.setState(false);
  73422. // Texture
  73423. for (var name in this._textures) {
  73424. this._effect.setTexture(name, this._textures[name]);
  73425. }
  73426. // Float
  73427. for (name in this._ints) {
  73428. this._effect.setInt(name, this._ints[name]);
  73429. }
  73430. // Float
  73431. for (name in this._floats) {
  73432. this._effect.setFloat(name, this._floats[name]);
  73433. }
  73434. // Floats
  73435. for (name in this._floatsArrays) {
  73436. this._effect.setArray(name, this._floatsArrays[name]);
  73437. }
  73438. // Color3
  73439. for (name in this._colors3) {
  73440. this._effect.setColor3(name, this._colors3[name]);
  73441. }
  73442. // Color4
  73443. for (name in this._colors4) {
  73444. var color = this._colors4[name];
  73445. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  73446. }
  73447. // Vector2
  73448. for (name in this._vectors2) {
  73449. this._effect.setVector2(name, this._vectors2[name]);
  73450. }
  73451. // Vector3
  73452. for (name in this._vectors3) {
  73453. this._effect.setVector3(name, this._vectors3[name]);
  73454. }
  73455. // Matrix
  73456. for (name in this._matrices) {
  73457. this._effect.setMatrix(name, this._matrices[name]);
  73458. }
  73459. if (!this._texture) {
  73460. return;
  73461. }
  73462. if (this.isCube) {
  73463. for (var face = 0; face < 6; face++) {
  73464. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  73465. // VBOs
  73466. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  73467. this._effect.setFloat("face", face);
  73468. // Clear
  73469. engine.clear(scene.clearColor, true, true, true);
  73470. // Draw order
  73471. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73472. // Mipmaps
  73473. if (face === 5) {
  73474. engine.generateMipMapsForCubemap(this._texture);
  73475. }
  73476. }
  73477. }
  73478. else {
  73479. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  73480. // VBOs
  73481. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  73482. // Clear
  73483. engine.clear(scene.clearColor, true, true, true);
  73484. // Draw order
  73485. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73486. }
  73487. // Unbind
  73488. engine.unBindFramebuffer(this._texture, this.isCube);
  73489. if (this.onGenerated) {
  73490. this.onGenerated();
  73491. }
  73492. };
  73493. ProceduralTexture.prototype.clone = function () {
  73494. var textureSize = this.getSize();
  73495. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  73496. // Base texture
  73497. newTexture.hasAlpha = this.hasAlpha;
  73498. newTexture.level = this.level;
  73499. // RenderTarget Texture
  73500. newTexture.coordinatesMode = this.coordinatesMode;
  73501. return newTexture;
  73502. };
  73503. ProceduralTexture.prototype.dispose = function () {
  73504. var scene = this.getScene();
  73505. if (!scene) {
  73506. return;
  73507. }
  73508. var index = scene.proceduralTextures.indexOf(this);
  73509. if (index >= 0) {
  73510. scene.proceduralTextures.splice(index, 1);
  73511. }
  73512. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73513. if (vertexBuffer) {
  73514. vertexBuffer.dispose();
  73515. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73516. }
  73517. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  73518. this._indexBuffer = null;
  73519. }
  73520. _super.prototype.dispose.call(this);
  73521. };
  73522. __decorate([
  73523. BABYLON.serialize()
  73524. ], ProceduralTexture.prototype, "_size", void 0);
  73525. __decorate([
  73526. BABYLON.serialize()
  73527. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  73528. __decorate([
  73529. BABYLON.serialize()
  73530. ], ProceduralTexture.prototype, "isEnabled", void 0);
  73531. __decorate([
  73532. BABYLON.serialize()
  73533. ], ProceduralTexture.prototype, "refreshRate", null);
  73534. return ProceduralTexture;
  73535. }(BABYLON.Texture));
  73536. BABYLON.ProceduralTexture = ProceduralTexture;
  73537. })(BABYLON || (BABYLON = {}));
  73538. //# sourceMappingURL=babylon.proceduralTexture.js.map
  73539. var BABYLON;
  73540. (function (BABYLON) {
  73541. var CustomProceduralTexture = /** @class */ (function (_super) {
  73542. __extends(CustomProceduralTexture, _super);
  73543. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  73544. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  73545. _this._animate = true;
  73546. _this._time = 0;
  73547. _this._texturePath = texturePath;
  73548. //Try to load json
  73549. _this.loadJson(texturePath);
  73550. _this.refreshRate = 1;
  73551. return _this;
  73552. }
  73553. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  73554. var _this = this;
  73555. var noConfigFile = function () {
  73556. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  73557. try {
  73558. _this.setFragment(_this._texturePath);
  73559. }
  73560. catch (ex) {
  73561. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  73562. }
  73563. };
  73564. var configFileUrl = jsonUrl + "/config.json";
  73565. var xhr = new XMLHttpRequest();
  73566. xhr.open("GET", configFileUrl, true);
  73567. xhr.addEventListener("load", function () {
  73568. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  73569. try {
  73570. _this._config = JSON.parse(xhr.response);
  73571. _this.updateShaderUniforms();
  73572. _this.updateTextures();
  73573. _this.setFragment(_this._texturePath + "/custom");
  73574. _this._animate = _this._config.animate;
  73575. _this.refreshRate = _this._config.refreshrate;
  73576. }
  73577. catch (ex) {
  73578. noConfigFile();
  73579. }
  73580. }
  73581. else {
  73582. noConfigFile();
  73583. }
  73584. }, false);
  73585. xhr.addEventListener("error", function () {
  73586. noConfigFile();
  73587. }, false);
  73588. try {
  73589. xhr.send();
  73590. }
  73591. catch (ex) {
  73592. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  73593. }
  73594. };
  73595. CustomProceduralTexture.prototype.isReady = function () {
  73596. if (!_super.prototype.isReady.call(this)) {
  73597. return false;
  73598. }
  73599. for (var name in this._textures) {
  73600. var texture = this._textures[name];
  73601. if (!texture.isReady()) {
  73602. return false;
  73603. }
  73604. }
  73605. return true;
  73606. };
  73607. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  73608. var scene = this.getScene();
  73609. if (this._animate && scene) {
  73610. this._time += scene.getAnimationRatio() * 0.03;
  73611. this.updateShaderUniforms();
  73612. }
  73613. _super.prototype.render.call(this, useCameraPostProcess);
  73614. };
  73615. CustomProceduralTexture.prototype.updateTextures = function () {
  73616. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  73617. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  73618. }
  73619. };
  73620. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  73621. if (this._config) {
  73622. for (var j = 0; j < this._config.uniforms.length; j++) {
  73623. var uniform = this._config.uniforms[j];
  73624. switch (uniform.type) {
  73625. case "float":
  73626. this.setFloat(uniform.name, uniform.value);
  73627. break;
  73628. case "color3":
  73629. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  73630. break;
  73631. case "color4":
  73632. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  73633. break;
  73634. case "vector2":
  73635. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  73636. break;
  73637. case "vector3":
  73638. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  73639. break;
  73640. }
  73641. }
  73642. }
  73643. this.setFloat("time", this._time);
  73644. };
  73645. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  73646. get: function () {
  73647. return this._animate;
  73648. },
  73649. set: function (value) {
  73650. this._animate = value;
  73651. },
  73652. enumerable: true,
  73653. configurable: true
  73654. });
  73655. return CustomProceduralTexture;
  73656. }(BABYLON.ProceduralTexture));
  73657. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  73658. })(BABYLON || (BABYLON = {}));
  73659. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  73660. var BABYLON;
  73661. (function (BABYLON) {
  73662. var FreeCameraGamepadInput = /** @class */ (function () {
  73663. function FreeCameraGamepadInput() {
  73664. this.gamepadAngularSensibility = 200;
  73665. this.gamepadMoveSensibility = 40;
  73666. // private members
  73667. this._cameraTransform = BABYLON.Matrix.Identity();
  73668. this._deltaTransform = BABYLON.Vector3.Zero();
  73669. this._vector3 = BABYLON.Vector3.Zero();
  73670. this._vector2 = BABYLON.Vector2.Zero();
  73671. }
  73672. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  73673. var _this = this;
  73674. var manager = this.camera.getScene().gamepadManager;
  73675. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  73676. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  73677. // prioritize XBOX gamepads.
  73678. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  73679. _this.gamepad = gamepad;
  73680. }
  73681. }
  73682. });
  73683. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  73684. if (_this.gamepad === gamepad) {
  73685. _this.gamepad = null;
  73686. }
  73687. });
  73688. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  73689. };
  73690. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  73691. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  73692. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  73693. this.gamepad = null;
  73694. };
  73695. FreeCameraGamepadInput.prototype.checkInputs = function () {
  73696. if (this.gamepad && this.gamepad.leftStick) {
  73697. var camera = this.camera;
  73698. var LSValues = this.gamepad.leftStick;
  73699. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  73700. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  73701. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  73702. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  73703. var RSValues = this.gamepad.rightStick;
  73704. if (RSValues) {
  73705. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  73706. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  73707. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  73708. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  73709. }
  73710. else {
  73711. RSValues = { x: 0, y: 0 };
  73712. }
  73713. if (!camera.rotationQuaternion) {
  73714. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  73715. }
  73716. else {
  73717. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  73718. }
  73719. var speed = camera._computeLocalCameraSpeed() * 50.0;
  73720. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  73721. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  73722. camera.cameraDirection.addInPlace(this._deltaTransform);
  73723. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  73724. camera.cameraRotation.addInPlace(this._vector2);
  73725. }
  73726. };
  73727. FreeCameraGamepadInput.prototype.getClassName = function () {
  73728. return "FreeCameraGamepadInput";
  73729. };
  73730. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  73731. return "gamepad";
  73732. };
  73733. __decorate([
  73734. BABYLON.serialize()
  73735. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  73736. __decorate([
  73737. BABYLON.serialize()
  73738. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  73739. return FreeCameraGamepadInput;
  73740. }());
  73741. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  73742. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  73743. })(BABYLON || (BABYLON = {}));
  73744. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  73745. var BABYLON;
  73746. (function (BABYLON) {
  73747. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  73748. function ArcRotateCameraGamepadInput() {
  73749. this.gamepadRotationSensibility = 80;
  73750. this.gamepadMoveSensibility = 40;
  73751. }
  73752. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  73753. var _this = this;
  73754. var manager = this.camera.getScene().gamepadManager;
  73755. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  73756. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  73757. // prioritize XBOX gamepads.
  73758. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  73759. _this.gamepad = gamepad;
  73760. }
  73761. }
  73762. });
  73763. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  73764. if (_this.gamepad === gamepad) {
  73765. _this.gamepad = null;
  73766. }
  73767. });
  73768. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  73769. };
  73770. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  73771. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  73772. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  73773. this.gamepad = null;
  73774. };
  73775. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  73776. if (this.gamepad) {
  73777. var camera = this.camera;
  73778. var RSValues = this.gamepad.rightStick;
  73779. if (RSValues) {
  73780. if (RSValues.x != 0) {
  73781. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  73782. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  73783. camera.inertialAlphaOffset += normalizedRX;
  73784. }
  73785. }
  73786. if (RSValues.y != 0) {
  73787. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  73788. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  73789. camera.inertialBetaOffset += normalizedRY;
  73790. }
  73791. }
  73792. }
  73793. var LSValues = this.gamepad.leftStick;
  73794. if (LSValues && LSValues.y != 0) {
  73795. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  73796. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  73797. this.camera.inertialRadiusOffset -= normalizedLY;
  73798. }
  73799. }
  73800. }
  73801. };
  73802. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  73803. return "ArcRotateCameraGamepadInput";
  73804. };
  73805. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  73806. return "gamepad";
  73807. };
  73808. __decorate([
  73809. BABYLON.serialize()
  73810. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  73811. __decorate([
  73812. BABYLON.serialize()
  73813. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  73814. return ArcRotateCameraGamepadInput;
  73815. }());
  73816. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  73817. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  73818. })(BABYLON || (BABYLON = {}));
  73819. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  73820. var BABYLON;
  73821. (function (BABYLON) {
  73822. var GamepadManager = /** @class */ (function () {
  73823. function GamepadManager(_scene) {
  73824. var _this = this;
  73825. this._scene = _scene;
  73826. this._babylonGamepads = [];
  73827. this._oneGamepadConnected = false;
  73828. /** @hidden */
  73829. this._isMonitoring = false;
  73830. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  73831. if (!BABYLON.Tools.IsWindowObjectExist()) {
  73832. this._gamepadEventSupported = false;
  73833. }
  73834. else {
  73835. this._gamepadEventSupported = 'GamepadEvent' in window;
  73836. this._gamepadSupport = (navigator.getGamepads ||
  73837. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  73838. }
  73839. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  73840. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  73841. for (var i in _this._babylonGamepads) {
  73842. var gamepad = _this._babylonGamepads[i];
  73843. if (gamepad && gamepad._isConnected) {
  73844. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  73845. }
  73846. }
  73847. });
  73848. this._onGamepadConnectedEvent = function (evt) {
  73849. var gamepad = evt.gamepad;
  73850. if (gamepad.index in _this._babylonGamepads) {
  73851. if (_this._babylonGamepads[gamepad.index].isConnected) {
  73852. return;
  73853. }
  73854. }
  73855. var newGamepad;
  73856. if (_this._babylonGamepads[gamepad.index]) {
  73857. newGamepad = _this._babylonGamepads[gamepad.index];
  73858. newGamepad.browserGamepad = gamepad;
  73859. newGamepad._isConnected = true;
  73860. }
  73861. else {
  73862. newGamepad = _this._addNewGamepad(gamepad);
  73863. }
  73864. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  73865. _this._startMonitoringGamepads();
  73866. };
  73867. this._onGamepadDisconnectedEvent = function (evt) {
  73868. var gamepad = evt.gamepad;
  73869. // Remove the gamepad from the list of gamepads to monitor.
  73870. for (var i in _this._babylonGamepads) {
  73871. if (_this._babylonGamepads[i].index === gamepad.index) {
  73872. var disconnectedGamepad = _this._babylonGamepads[i];
  73873. disconnectedGamepad._isConnected = false;
  73874. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  73875. break;
  73876. }
  73877. }
  73878. };
  73879. if (this._gamepadSupport) {
  73880. //first add already-connected gamepads
  73881. this._updateGamepadObjects();
  73882. if (this._babylonGamepads.length) {
  73883. this._startMonitoringGamepads();
  73884. }
  73885. // Checking if the gamepad connected event is supported (like in Firefox)
  73886. if (this._gamepadEventSupported) {
  73887. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  73888. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  73889. }
  73890. else {
  73891. this._startMonitoringGamepads();
  73892. }
  73893. }
  73894. }
  73895. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  73896. get: function () {
  73897. return this._babylonGamepads;
  73898. },
  73899. enumerable: true,
  73900. configurable: true
  73901. });
  73902. GamepadManager.prototype.getGamepadByType = function (type) {
  73903. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  73904. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  73905. var gamepad = _a[_i];
  73906. if (gamepad && gamepad.type === type) {
  73907. return gamepad;
  73908. }
  73909. }
  73910. return null;
  73911. };
  73912. GamepadManager.prototype.dispose = function () {
  73913. if (this._gamepadEventSupported) {
  73914. if (this._onGamepadConnectedEvent) {
  73915. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  73916. }
  73917. if (this._onGamepadDisconnectedEvent) {
  73918. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  73919. }
  73920. this._onGamepadConnectedEvent = null;
  73921. this._onGamepadDisconnectedEvent = null;
  73922. }
  73923. this._babylonGamepads.forEach(function (gamepad) {
  73924. gamepad.dispose();
  73925. });
  73926. this.onGamepadConnectedObservable.clear();
  73927. this.onGamepadDisconnectedObservable.clear();
  73928. this._oneGamepadConnected = false;
  73929. this._stopMonitoringGamepads();
  73930. this._babylonGamepads = [];
  73931. };
  73932. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  73933. if (!this._oneGamepadConnected) {
  73934. this._oneGamepadConnected = true;
  73935. }
  73936. var newGamepad;
  73937. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  73938. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  73939. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  73940. }
  73941. // if pose is supported, use the (WebVR) pose enabled controller
  73942. else if (gamepad.pose) {
  73943. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  73944. }
  73945. else {
  73946. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  73947. }
  73948. this._babylonGamepads[newGamepad.index] = newGamepad;
  73949. return newGamepad;
  73950. };
  73951. GamepadManager.prototype._startMonitoringGamepads = function () {
  73952. if (!this._isMonitoring) {
  73953. this._isMonitoring = true;
  73954. //back-comp
  73955. if (!this._scene) {
  73956. this._checkGamepadsStatus();
  73957. }
  73958. }
  73959. };
  73960. GamepadManager.prototype._stopMonitoringGamepads = function () {
  73961. this._isMonitoring = false;
  73962. };
  73963. /** @hidden */
  73964. GamepadManager.prototype._checkGamepadsStatus = function () {
  73965. var _this = this;
  73966. // Hack to be compatible Chrome
  73967. this._updateGamepadObjects();
  73968. for (var i in this._babylonGamepads) {
  73969. var gamepad = this._babylonGamepads[i];
  73970. if (!gamepad || !gamepad.isConnected) {
  73971. continue;
  73972. }
  73973. gamepad.update();
  73974. }
  73975. if (this._isMonitoring && !this._scene) {
  73976. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  73977. }
  73978. };
  73979. // This function is called only on Chrome, which does not properly support
  73980. // connection/disconnection events and forces you to recopy again the gamepad object
  73981. GamepadManager.prototype._updateGamepadObjects = function () {
  73982. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  73983. for (var i = 0; i < gamepads.length; i++) {
  73984. var gamepad = gamepads[i];
  73985. if (gamepad) {
  73986. if (!this._babylonGamepads[gamepad.index]) {
  73987. var newGamepad = this._addNewGamepad(gamepad);
  73988. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  73989. }
  73990. else {
  73991. // Forced to copy again this object for Chrome for unknown reason
  73992. this._babylonGamepads[i].browserGamepad = gamepad;
  73993. if (!this._babylonGamepads[i].isConnected) {
  73994. this._babylonGamepads[i]._isConnected = true;
  73995. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  73996. }
  73997. }
  73998. }
  73999. }
  74000. };
  74001. return GamepadManager;
  74002. }());
  74003. BABYLON.GamepadManager = GamepadManager;
  74004. })(BABYLON || (BABYLON = {}));
  74005. //# sourceMappingURL=babylon.gamepadManager.js.map
  74006. var BABYLON;
  74007. (function (BABYLON) {
  74008. var StickValues = /** @class */ (function () {
  74009. function StickValues(x, y) {
  74010. this.x = x;
  74011. this.y = y;
  74012. }
  74013. return StickValues;
  74014. }());
  74015. BABYLON.StickValues = StickValues;
  74016. var Gamepad = /** @class */ (function () {
  74017. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  74018. if (leftStickX === void 0) { leftStickX = 0; }
  74019. if (leftStickY === void 0) { leftStickY = 1; }
  74020. if (rightStickX === void 0) { rightStickX = 2; }
  74021. if (rightStickY === void 0) { rightStickY = 3; }
  74022. this.id = id;
  74023. this.index = index;
  74024. this.browserGamepad = browserGamepad;
  74025. this._leftStick = { x: 0, y: 0 };
  74026. this._rightStick = { x: 0, y: 0 };
  74027. /** @hidden */
  74028. this._isConnected = true;
  74029. this._invertLeftStickY = false;
  74030. this.type = Gamepad.GAMEPAD;
  74031. this._leftStickAxisX = leftStickX;
  74032. this._leftStickAxisY = leftStickY;
  74033. this._rightStickAxisX = rightStickX;
  74034. this._rightStickAxisY = rightStickY;
  74035. if (this.browserGamepad.axes.length >= 2) {
  74036. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  74037. }
  74038. if (this.browserGamepad.axes.length >= 4) {
  74039. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  74040. }
  74041. }
  74042. Object.defineProperty(Gamepad.prototype, "isConnected", {
  74043. get: function () {
  74044. return this._isConnected;
  74045. },
  74046. enumerable: true,
  74047. configurable: true
  74048. });
  74049. Gamepad.prototype.onleftstickchanged = function (callback) {
  74050. this._onleftstickchanged = callback;
  74051. };
  74052. Gamepad.prototype.onrightstickchanged = function (callback) {
  74053. this._onrightstickchanged = callback;
  74054. };
  74055. Object.defineProperty(Gamepad.prototype, "leftStick", {
  74056. get: function () {
  74057. return this._leftStick;
  74058. },
  74059. set: function (newValues) {
  74060. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  74061. this._onleftstickchanged(newValues);
  74062. }
  74063. this._leftStick = newValues;
  74064. },
  74065. enumerable: true,
  74066. configurable: true
  74067. });
  74068. Object.defineProperty(Gamepad.prototype, "rightStick", {
  74069. get: function () {
  74070. return this._rightStick;
  74071. },
  74072. set: function (newValues) {
  74073. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  74074. this._onrightstickchanged(newValues);
  74075. }
  74076. this._rightStick = newValues;
  74077. },
  74078. enumerable: true,
  74079. configurable: true
  74080. });
  74081. Gamepad.prototype.update = function () {
  74082. if (this._leftStick) {
  74083. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  74084. if (this._invertLeftStickY) {
  74085. this.leftStick.y *= -1;
  74086. }
  74087. }
  74088. if (this._rightStick) {
  74089. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  74090. }
  74091. };
  74092. Gamepad.prototype.dispose = function () {
  74093. };
  74094. Gamepad.GAMEPAD = 0;
  74095. Gamepad.GENERIC = 1;
  74096. Gamepad.XBOX = 2;
  74097. Gamepad.POSE_ENABLED = 3;
  74098. return Gamepad;
  74099. }());
  74100. BABYLON.Gamepad = Gamepad;
  74101. var GenericPad = /** @class */ (function (_super) {
  74102. __extends(GenericPad, _super);
  74103. function GenericPad(id, index, browserGamepad) {
  74104. var _this = _super.call(this, id, index, browserGamepad) || this;
  74105. _this.onButtonDownObservable = new BABYLON.Observable();
  74106. _this.onButtonUpObservable = new BABYLON.Observable();
  74107. _this.type = Gamepad.GENERIC;
  74108. _this._buttons = new Array(browserGamepad.buttons.length);
  74109. return _this;
  74110. }
  74111. GenericPad.prototype.onbuttondown = function (callback) {
  74112. this._onbuttondown = callback;
  74113. };
  74114. GenericPad.prototype.onbuttonup = function (callback) {
  74115. this._onbuttonup = callback;
  74116. };
  74117. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  74118. if (newValue !== currentValue) {
  74119. if (newValue === 1) {
  74120. if (this._onbuttondown) {
  74121. this._onbuttondown(buttonIndex);
  74122. }
  74123. this.onButtonDownObservable.notifyObservers(buttonIndex);
  74124. }
  74125. if (newValue === 0) {
  74126. if (this._onbuttonup) {
  74127. this._onbuttonup(buttonIndex);
  74128. }
  74129. this.onButtonUpObservable.notifyObservers(buttonIndex);
  74130. }
  74131. }
  74132. return newValue;
  74133. };
  74134. GenericPad.prototype.update = function () {
  74135. _super.prototype.update.call(this);
  74136. for (var index = 0; index < this._buttons.length; index++) {
  74137. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  74138. }
  74139. };
  74140. GenericPad.prototype.dispose = function () {
  74141. _super.prototype.dispose.call(this);
  74142. this.onButtonDownObservable.clear();
  74143. this.onButtonUpObservable.clear();
  74144. };
  74145. return GenericPad;
  74146. }(Gamepad));
  74147. BABYLON.GenericPad = GenericPad;
  74148. })(BABYLON || (BABYLON = {}));
  74149. //# sourceMappingURL=babylon.gamepad.js.map
  74150. var BABYLON;
  74151. (function (BABYLON) {
  74152. /**
  74153. * Defines supported buttons for XBox360 compatible gamepads
  74154. */
  74155. var Xbox360Button;
  74156. (function (Xbox360Button) {
  74157. /** A */
  74158. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  74159. /** B */
  74160. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  74161. /** X */
  74162. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  74163. /** Y */
  74164. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  74165. /** Start */
  74166. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  74167. /** Back */
  74168. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  74169. /** Left button */
  74170. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  74171. /** Right button */
  74172. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  74173. /** Left stick */
  74174. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  74175. /** Right stick */
  74176. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  74177. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  74178. /** Defines values for XBox360 DPad */
  74179. var Xbox360Dpad;
  74180. (function (Xbox360Dpad) {
  74181. /** Up */
  74182. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  74183. /** Down */
  74184. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  74185. /** Left */
  74186. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  74187. /** Right */
  74188. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  74189. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  74190. /**
  74191. * Defines a XBox360 gamepad
  74192. */
  74193. var Xbox360Pad = /** @class */ (function (_super) {
  74194. __extends(Xbox360Pad, _super);
  74195. /**
  74196. * Creates a new XBox360 gamepad object
  74197. * @param id defines the id of this gamepad
  74198. * @param index defines its index
  74199. * @param gamepad defines the internal HTML gamepad object
  74200. * @param xboxOne defines if it is a XBox One gamepad
  74201. */
  74202. function Xbox360Pad(id, index, gamepad, xboxOne) {
  74203. if (xboxOne === void 0) { xboxOne = false; }
  74204. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  74205. _this._leftTrigger = 0;
  74206. _this._rightTrigger = 0;
  74207. /** Observable raised when a button is pressed */
  74208. _this.onButtonDownObservable = new BABYLON.Observable();
  74209. /** Observable raised when a button is released */
  74210. _this.onButtonUpObservable = new BABYLON.Observable();
  74211. /** Observable raised when a pad is pressed */
  74212. _this.onPadDownObservable = new BABYLON.Observable();
  74213. /** Observable raised when a pad is released */
  74214. _this.onPadUpObservable = new BABYLON.Observable();
  74215. _this._buttonA = 0;
  74216. _this._buttonB = 0;
  74217. _this._buttonX = 0;
  74218. _this._buttonY = 0;
  74219. _this._buttonBack = 0;
  74220. _this._buttonStart = 0;
  74221. _this._buttonLB = 0;
  74222. _this._buttonRB = 0;
  74223. _this._buttonLeftStick = 0;
  74224. _this._buttonRightStick = 0;
  74225. _this._dPadUp = 0;
  74226. _this._dPadDown = 0;
  74227. _this._dPadLeft = 0;
  74228. _this._dPadRight = 0;
  74229. _this._isXboxOnePad = false;
  74230. _this.type = BABYLON.Gamepad.XBOX;
  74231. _this._isXboxOnePad = xboxOne;
  74232. return _this;
  74233. }
  74234. /**
  74235. * Defines the callback to call when left trigger is pressed
  74236. * @param callback defines the callback to use
  74237. */
  74238. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  74239. this._onlefttriggerchanged = callback;
  74240. };
  74241. /**
  74242. * Defines the callback to call when right trigger is pressed
  74243. * @param callback defines the callback to use
  74244. */
  74245. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  74246. this._onrighttriggerchanged = callback;
  74247. };
  74248. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  74249. /**
  74250. * Gets or sets left trigger value
  74251. */
  74252. get: function () {
  74253. return this._leftTrigger;
  74254. },
  74255. set: function (newValue) {
  74256. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  74257. this._onlefttriggerchanged(newValue);
  74258. }
  74259. this._leftTrigger = newValue;
  74260. },
  74261. enumerable: true,
  74262. configurable: true
  74263. });
  74264. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  74265. /**
  74266. * Gets or sets right trigger value
  74267. */
  74268. get: function () {
  74269. return this._rightTrigger;
  74270. },
  74271. set: function (newValue) {
  74272. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  74273. this._onrighttriggerchanged(newValue);
  74274. }
  74275. this._rightTrigger = newValue;
  74276. },
  74277. enumerable: true,
  74278. configurable: true
  74279. });
  74280. /**
  74281. * Defines the callback to call when a button is pressed
  74282. * @param callback defines the callback to use
  74283. */
  74284. Xbox360Pad.prototype.onbuttondown = function (callback) {
  74285. this._onbuttondown = callback;
  74286. };
  74287. /**
  74288. * Defines the callback to call when a button is released
  74289. * @param callback defines the callback to use
  74290. */
  74291. Xbox360Pad.prototype.onbuttonup = function (callback) {
  74292. this._onbuttonup = callback;
  74293. };
  74294. /**
  74295. * Defines the callback to call when a pad is pressed
  74296. * @param callback defines the callback to use
  74297. */
  74298. Xbox360Pad.prototype.ondpaddown = function (callback) {
  74299. this._ondpaddown = callback;
  74300. };
  74301. /**
  74302. * Defines the callback to call when a pad is released
  74303. * @param callback defines the callback to use
  74304. */
  74305. Xbox360Pad.prototype.ondpadup = function (callback) {
  74306. this._ondpadup = callback;
  74307. };
  74308. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  74309. if (newValue !== currentValue) {
  74310. if (newValue === 1) {
  74311. if (this._onbuttondown) {
  74312. this._onbuttondown(buttonType);
  74313. }
  74314. this.onButtonDownObservable.notifyObservers(buttonType);
  74315. }
  74316. if (newValue === 0) {
  74317. if (this._onbuttonup) {
  74318. this._onbuttonup(buttonType);
  74319. }
  74320. this.onButtonUpObservable.notifyObservers(buttonType);
  74321. }
  74322. }
  74323. return newValue;
  74324. };
  74325. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  74326. if (newValue !== currentValue) {
  74327. if (newValue === 1) {
  74328. if (this._ondpaddown) {
  74329. this._ondpaddown(buttonType);
  74330. }
  74331. this.onPadDownObservable.notifyObservers(buttonType);
  74332. }
  74333. if (newValue === 0) {
  74334. if (this._ondpadup) {
  74335. this._ondpadup(buttonType);
  74336. }
  74337. this.onPadUpObservable.notifyObservers(buttonType);
  74338. }
  74339. }
  74340. return newValue;
  74341. };
  74342. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  74343. /** Gets or sets value of A button */
  74344. get: function () {
  74345. return this._buttonA;
  74346. },
  74347. set: function (value) {
  74348. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  74349. },
  74350. enumerable: true,
  74351. configurable: true
  74352. });
  74353. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  74354. /** Gets or sets value of B button */
  74355. get: function () {
  74356. return this._buttonB;
  74357. },
  74358. set: function (value) {
  74359. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  74360. },
  74361. enumerable: true,
  74362. configurable: true
  74363. });
  74364. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  74365. /** Gets or sets value of X button */
  74366. get: function () {
  74367. return this._buttonX;
  74368. },
  74369. set: function (value) {
  74370. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  74371. },
  74372. enumerable: true,
  74373. configurable: true
  74374. });
  74375. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  74376. /** Gets or sets value of Y button */
  74377. get: function () {
  74378. return this._buttonY;
  74379. },
  74380. set: function (value) {
  74381. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  74382. },
  74383. enumerable: true,
  74384. configurable: true
  74385. });
  74386. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  74387. /** Gets or sets value of Start button */
  74388. get: function () {
  74389. return this._buttonStart;
  74390. },
  74391. set: function (value) {
  74392. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  74393. },
  74394. enumerable: true,
  74395. configurable: true
  74396. });
  74397. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  74398. /** Gets or sets value of Back button */
  74399. get: function () {
  74400. return this._buttonBack;
  74401. },
  74402. set: function (value) {
  74403. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  74404. },
  74405. enumerable: true,
  74406. configurable: true
  74407. });
  74408. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  74409. /** Gets or sets value of Left button */
  74410. get: function () {
  74411. return this._buttonLB;
  74412. },
  74413. set: function (value) {
  74414. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  74415. },
  74416. enumerable: true,
  74417. configurable: true
  74418. });
  74419. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  74420. /** Gets or sets value of Right button */
  74421. get: function () {
  74422. return this._buttonRB;
  74423. },
  74424. set: function (value) {
  74425. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  74426. },
  74427. enumerable: true,
  74428. configurable: true
  74429. });
  74430. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  74431. /** Gets or sets value of left stick */
  74432. get: function () {
  74433. return this._buttonLeftStick;
  74434. },
  74435. set: function (value) {
  74436. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  74437. },
  74438. enumerable: true,
  74439. configurable: true
  74440. });
  74441. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  74442. /** Gets or sets value of right stick */
  74443. get: function () {
  74444. return this._buttonRightStick;
  74445. },
  74446. set: function (value) {
  74447. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  74448. },
  74449. enumerable: true,
  74450. configurable: true
  74451. });
  74452. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  74453. /** Gets or sets value of DPad up */
  74454. get: function () {
  74455. return this._dPadUp;
  74456. },
  74457. set: function (value) {
  74458. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  74459. },
  74460. enumerable: true,
  74461. configurable: true
  74462. });
  74463. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  74464. /** Gets or sets value of DPad down */
  74465. get: function () {
  74466. return this._dPadDown;
  74467. },
  74468. set: function (value) {
  74469. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  74470. },
  74471. enumerable: true,
  74472. configurable: true
  74473. });
  74474. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  74475. /** Gets or sets value of DPad left */
  74476. get: function () {
  74477. return this._dPadLeft;
  74478. },
  74479. set: function (value) {
  74480. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  74481. },
  74482. enumerable: true,
  74483. configurable: true
  74484. });
  74485. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  74486. /** Gets or sets value of DPad right */
  74487. get: function () {
  74488. return this._dPadRight;
  74489. },
  74490. set: function (value) {
  74491. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  74492. },
  74493. enumerable: true,
  74494. configurable: true
  74495. });
  74496. /**
  74497. * Force the gamepad to synchronize with device values
  74498. */
  74499. Xbox360Pad.prototype.update = function () {
  74500. _super.prototype.update.call(this);
  74501. if (this._isXboxOnePad) {
  74502. this.buttonA = this.browserGamepad.buttons[0].value;
  74503. this.buttonB = this.browserGamepad.buttons[1].value;
  74504. this.buttonX = this.browserGamepad.buttons[2].value;
  74505. this.buttonY = this.browserGamepad.buttons[3].value;
  74506. this.buttonLB = this.browserGamepad.buttons[4].value;
  74507. this.buttonRB = this.browserGamepad.buttons[5].value;
  74508. this.leftTrigger = this.browserGamepad.axes[2];
  74509. this.rightTrigger = this.browserGamepad.axes[5];
  74510. this.buttonBack = this.browserGamepad.buttons[9].value;
  74511. this.buttonStart = this.browserGamepad.buttons[8].value;
  74512. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  74513. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  74514. this.dPadUp = this.browserGamepad.buttons[11].value;
  74515. this.dPadDown = this.browserGamepad.buttons[12].value;
  74516. this.dPadLeft = this.browserGamepad.buttons[13].value;
  74517. this.dPadRight = this.browserGamepad.buttons[14].value;
  74518. }
  74519. else {
  74520. this.buttonA = this.browserGamepad.buttons[0].value;
  74521. this.buttonB = this.browserGamepad.buttons[1].value;
  74522. this.buttonX = this.browserGamepad.buttons[2].value;
  74523. this.buttonY = this.browserGamepad.buttons[3].value;
  74524. this.buttonLB = this.browserGamepad.buttons[4].value;
  74525. this.buttonRB = this.browserGamepad.buttons[5].value;
  74526. this.leftTrigger = this.browserGamepad.buttons[6].value;
  74527. this.rightTrigger = this.browserGamepad.buttons[7].value;
  74528. this.buttonBack = this.browserGamepad.buttons[8].value;
  74529. this.buttonStart = this.browserGamepad.buttons[9].value;
  74530. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  74531. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  74532. this.dPadUp = this.browserGamepad.buttons[12].value;
  74533. this.dPadDown = this.browserGamepad.buttons[13].value;
  74534. this.dPadLeft = this.browserGamepad.buttons[14].value;
  74535. this.dPadRight = this.browserGamepad.buttons[15].value;
  74536. }
  74537. };
  74538. Xbox360Pad.prototype.dispose = function () {
  74539. _super.prototype.dispose.call(this);
  74540. this.onButtonDownObservable.clear();
  74541. this.onButtonUpObservable.clear();
  74542. this.onPadDownObservable.clear();
  74543. this.onPadUpObservable.clear();
  74544. };
  74545. return Xbox360Pad;
  74546. }(BABYLON.Gamepad));
  74547. BABYLON.Xbox360Pad = Xbox360Pad;
  74548. })(BABYLON || (BABYLON = {}));
  74549. //# sourceMappingURL=babylon.xboxGamepad.js.map
  74550. var BABYLON;
  74551. (function (BABYLON) {
  74552. /**
  74553. * Defines the types of pose enabled controllers that are supported
  74554. */
  74555. var PoseEnabledControllerType;
  74556. (function (PoseEnabledControllerType) {
  74557. /**
  74558. * HTC Vive
  74559. */
  74560. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  74561. /**
  74562. * Oculus Rift
  74563. */
  74564. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  74565. /**
  74566. * Windows mixed reality
  74567. */
  74568. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  74569. /**
  74570. * Samsung gear VR
  74571. */
  74572. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  74573. /**
  74574. * Google Daydream
  74575. */
  74576. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  74577. /**
  74578. * Generic
  74579. */
  74580. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  74581. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  74582. /**
  74583. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  74584. */
  74585. var PoseEnabledControllerHelper = /** @class */ (function () {
  74586. function PoseEnabledControllerHelper() {
  74587. }
  74588. /**
  74589. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  74590. * @param vrGamepad the gamepad to initialized
  74591. * @returns a vr controller of the type the gamepad identified as
  74592. */
  74593. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  74594. // Oculus Touch
  74595. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  74596. return new BABYLON.OculusTouchController(vrGamepad);
  74597. }
  74598. // Windows Mixed Reality controllers
  74599. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  74600. return new BABYLON.WindowsMotionController(vrGamepad);
  74601. }
  74602. // HTC Vive
  74603. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  74604. return new BABYLON.ViveController(vrGamepad);
  74605. }
  74606. // Samsung/Oculus Gear VR or Oculus Go
  74607. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  74608. return new BABYLON.GearVRController(vrGamepad);
  74609. }
  74610. // Google Daydream
  74611. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  74612. return new BABYLON.DaydreamController(vrGamepad);
  74613. }
  74614. // Generic
  74615. else {
  74616. return new BABYLON.GenericController(vrGamepad);
  74617. }
  74618. };
  74619. return PoseEnabledControllerHelper;
  74620. }());
  74621. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  74622. /**
  74623. * Defines the PoseEnabledController object that contains state of a vr capable controller
  74624. */
  74625. var PoseEnabledController = /** @class */ (function (_super) {
  74626. __extends(PoseEnabledController, _super);
  74627. /**
  74628. * Creates a new PoseEnabledController from a gamepad
  74629. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  74630. */
  74631. function PoseEnabledController(browserGamepad) {
  74632. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  74633. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  74634. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  74635. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  74636. /**
  74637. * The device position in babylon space
  74638. */
  74639. _this.devicePosition = BABYLON.Vector3.Zero();
  74640. /**
  74641. * The device rotation in babylon space
  74642. */
  74643. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  74644. /**
  74645. * The scale factor of the device in babylon space
  74646. */
  74647. _this.deviceScaleFactor = 1;
  74648. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  74649. /**
  74650. * Internal, matrix used to convert room space to babylon space
  74651. * @hidden
  74652. */
  74653. _this._deviceToWorld = BABYLON.Matrix.Identity();
  74654. /**
  74655. * Node to be used when casting a ray from the controller
  74656. * @hidden
  74657. */
  74658. _this._pointingPoseNode = null;
  74659. _this._workingMatrix = BABYLON.Matrix.Identity();
  74660. /**
  74661. * @hidden
  74662. */
  74663. _this._meshAttachedObservable = new BABYLON.Observable();
  74664. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  74665. _this.controllerType = PoseEnabledControllerType.GENERIC;
  74666. _this.position = BABYLON.Vector3.Zero();
  74667. _this.rotationQuaternion = new BABYLON.Quaternion();
  74668. _this._calculatedPosition = BABYLON.Vector3.Zero();
  74669. _this._calculatedRotation = new BABYLON.Quaternion();
  74670. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  74671. return _this;
  74672. }
  74673. /**
  74674. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  74675. */
  74676. PoseEnabledController.prototype.update = function () {
  74677. _super.prototype.update.call(this);
  74678. this._updatePoseAndMesh();
  74679. };
  74680. /**
  74681. * Updates only the pose device and mesh without doing any button event checking
  74682. */
  74683. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  74684. var pose = this.browserGamepad.pose;
  74685. this.updateFromDevice(pose);
  74686. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  74687. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  74688. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  74689. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  74690. if (this._mesh) {
  74691. this._mesh.position.copyFrom(this.devicePosition);
  74692. if (this._mesh.rotationQuaternion) {
  74693. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  74694. }
  74695. }
  74696. };
  74697. /**
  74698. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  74699. * @param poseData raw pose fromthe device
  74700. */
  74701. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  74702. if (poseData) {
  74703. this.rawPose = poseData;
  74704. if (poseData.position) {
  74705. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  74706. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  74707. this._deviceRoomPosition.z *= -1;
  74708. }
  74709. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  74710. this._calculatedPosition.addInPlace(this.position);
  74711. }
  74712. var pose = this.rawPose;
  74713. if (poseData.orientation && pose.orientation) {
  74714. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  74715. if (this._mesh) {
  74716. if (this._mesh.getScene().useRightHandedSystem) {
  74717. this._deviceRoomRotationQuaternion.z *= -1;
  74718. this._deviceRoomRotationQuaternion.w *= -1;
  74719. }
  74720. else {
  74721. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  74722. }
  74723. }
  74724. // if the camera is set, rotate to the camera's rotation
  74725. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  74726. }
  74727. }
  74728. };
  74729. /**
  74730. * Attaches a mesh to the controller
  74731. * @param mesh the mesh to be attached
  74732. */
  74733. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  74734. if (this._mesh) {
  74735. this._mesh.parent = null;
  74736. }
  74737. this._mesh = mesh;
  74738. if (this._poseControlledCamera) {
  74739. this._mesh.parent = this._poseControlledCamera;
  74740. }
  74741. if (!this._mesh.rotationQuaternion) {
  74742. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  74743. }
  74744. // 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
  74745. this._updatePoseAndMesh();
  74746. if (this._pointingPoseNode) {
  74747. var parents = [];
  74748. var obj = this._pointingPoseNode;
  74749. while (obj.parent) {
  74750. parents.push(obj.parent);
  74751. obj = obj.parent;
  74752. }
  74753. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  74754. }
  74755. this._meshAttachedObservable.notifyObservers(mesh);
  74756. };
  74757. /**
  74758. * Attaches the controllers mesh to a camera
  74759. * @param camera the camera the mesh should be attached to
  74760. */
  74761. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  74762. this._poseControlledCamera = camera;
  74763. if (this._mesh) {
  74764. this._mesh.parent = this._poseControlledCamera;
  74765. }
  74766. };
  74767. /**
  74768. * Disposes of the controller
  74769. */
  74770. PoseEnabledController.prototype.dispose = function () {
  74771. if (this._mesh) {
  74772. this._mesh.dispose();
  74773. }
  74774. this._mesh = null;
  74775. _super.prototype.dispose.call(this);
  74776. };
  74777. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  74778. /**
  74779. * The mesh that is attached to the controller
  74780. */
  74781. get: function () {
  74782. return this._mesh;
  74783. },
  74784. enumerable: true,
  74785. configurable: true
  74786. });
  74787. /**
  74788. * Gets the ray of the controller in the direction the controller is pointing
  74789. * @param length the length the resulting ray should be
  74790. * @returns a ray in the direction the controller is pointing
  74791. */
  74792. PoseEnabledController.prototype.getForwardRay = function (length) {
  74793. if (length === void 0) { length = 100; }
  74794. if (!this.mesh) {
  74795. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  74796. }
  74797. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  74798. var origin = m.getTranslation();
  74799. var forward = new BABYLON.Vector3(0, 0, -1);
  74800. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  74801. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  74802. return new BABYLON.Ray(origin, direction, length);
  74803. };
  74804. /**
  74805. * Name of the child mesh that can be used to cast a ray from the controller
  74806. */
  74807. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  74808. return PoseEnabledController;
  74809. }(BABYLON.Gamepad));
  74810. BABYLON.PoseEnabledController = PoseEnabledController;
  74811. })(BABYLON || (BABYLON = {}));
  74812. //# sourceMappingURL=babylon.poseEnabledController.js.map
  74813. var BABYLON;
  74814. (function (BABYLON) {
  74815. /**
  74816. * Defines the WebVRController object that represents controllers tracked in 3D space
  74817. */
  74818. var WebVRController = /** @class */ (function (_super) {
  74819. __extends(WebVRController, _super);
  74820. /**
  74821. * Creates a new WebVRController from a gamepad
  74822. * @param vrGamepad the gamepad that the WebVRController should be created from
  74823. */
  74824. function WebVRController(vrGamepad) {
  74825. var _this = _super.call(this, vrGamepad) || this;
  74826. // Observables
  74827. /**
  74828. * Fired when the trigger state has changed
  74829. */
  74830. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  74831. /**
  74832. * Fired when the main button state has changed
  74833. */
  74834. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  74835. /**
  74836. * Fired when the secondary button state has changed
  74837. */
  74838. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  74839. /**
  74840. * Fired when the pad state has changed
  74841. */
  74842. _this.onPadStateChangedObservable = new BABYLON.Observable();
  74843. /**
  74844. * Fired when controllers stick values have changed
  74845. */
  74846. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  74847. /**
  74848. * X and Y axis corrisponding to the controllers joystick
  74849. */
  74850. _this.pad = { x: 0, y: 0 };
  74851. // avoid GC, store state in a tmp object
  74852. _this._changes = {
  74853. pressChanged: false,
  74854. touchChanged: false,
  74855. valueChanged: false,
  74856. changed: false
  74857. };
  74858. _this._buttons = new Array(vrGamepad.buttons.length);
  74859. _this.hand = vrGamepad.hand;
  74860. return _this;
  74861. }
  74862. /**
  74863. * Fired when a controller button's state has changed
  74864. * @param callback the callback containing the button that was modified
  74865. */
  74866. WebVRController.prototype.onButtonStateChange = function (callback) {
  74867. this._onButtonStateChange = callback;
  74868. };
  74869. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  74870. /**
  74871. * The default controller model for the controller
  74872. */
  74873. get: function () {
  74874. return this._defaultModel;
  74875. },
  74876. enumerable: true,
  74877. configurable: true
  74878. });
  74879. /**
  74880. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  74881. */
  74882. WebVRController.prototype.update = function () {
  74883. _super.prototype.update.call(this);
  74884. for (var index = 0; index < this._buttons.length; index++) {
  74885. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  74886. }
  74887. ;
  74888. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  74889. this.pad.x = this.leftStick.x;
  74890. this.pad.y = this.leftStick.y;
  74891. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  74892. }
  74893. };
  74894. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  74895. if (!newState) {
  74896. newState = {
  74897. pressed: false,
  74898. touched: false,
  74899. value: 0
  74900. };
  74901. }
  74902. if (!currentState) {
  74903. this._buttons[buttonIndex] = {
  74904. pressed: newState.pressed,
  74905. touched: newState.touched,
  74906. value: newState.value
  74907. };
  74908. return;
  74909. }
  74910. this._checkChanges(newState, currentState);
  74911. if (this._changes.changed) {
  74912. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  74913. this._handleButtonChange(buttonIndex, newState, this._changes);
  74914. }
  74915. this._buttons[buttonIndex].pressed = newState.pressed;
  74916. this._buttons[buttonIndex].touched = newState.touched;
  74917. // oculus triggers are never 0, thou not touched.
  74918. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  74919. };
  74920. WebVRController.prototype._checkChanges = function (newState, currentState) {
  74921. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  74922. this._changes.touchChanged = newState.touched !== currentState.touched;
  74923. this._changes.valueChanged = newState.value !== currentState.value;
  74924. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  74925. return this._changes;
  74926. };
  74927. /**
  74928. * Disposes of th webVRCOntroller
  74929. */
  74930. WebVRController.prototype.dispose = function () {
  74931. _super.prototype.dispose.call(this);
  74932. this.onTriggerStateChangedObservable.clear();
  74933. this.onMainButtonStateChangedObservable.clear();
  74934. this.onSecondaryButtonStateChangedObservable.clear();
  74935. this.onPadStateChangedObservable.clear();
  74936. this.onPadValuesChangedObservable.clear();
  74937. };
  74938. return WebVRController;
  74939. }(BABYLON.PoseEnabledController));
  74940. BABYLON.WebVRController = WebVRController;
  74941. })(BABYLON || (BABYLON = {}));
  74942. //# sourceMappingURL=babylon.webVRController.js.map
  74943. var BABYLON;
  74944. (function (BABYLON) {
  74945. /**
  74946. * Oculus Touch Controller
  74947. */
  74948. var OculusTouchController = /** @class */ (function (_super) {
  74949. __extends(OculusTouchController, _super);
  74950. /**
  74951. * Creates a new OculusTouchController from a gamepad
  74952. * @param vrGamepad the gamepad that the controller should be created from
  74953. */
  74954. function OculusTouchController(vrGamepad) {
  74955. var _this = _super.call(this, vrGamepad) || this;
  74956. /**
  74957. * Fired when the secondary trigger on this controller is modified
  74958. */
  74959. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  74960. /**
  74961. * Fired when the thumb rest on this controller is modified
  74962. */
  74963. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  74964. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  74965. return _this;
  74966. }
  74967. /**
  74968. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74969. * @param scene scene in which to add meshes
  74970. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74971. */
  74972. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74973. var _this = this;
  74974. var meshName;
  74975. // Hand
  74976. if (this.hand === 'left') {
  74977. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  74978. }
  74979. else { // Right is the default if no hand is specified
  74980. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  74981. }
  74982. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  74983. /*
  74984. Parent Mesh name: oculus_touch_left
  74985. - body
  74986. - trigger
  74987. - thumbstick
  74988. - grip
  74989. - button_y
  74990. - button_x
  74991. - button_enter
  74992. */
  74993. _this._defaultModel = newMeshes[1];
  74994. _this.attachToMesh(_this._defaultModel);
  74995. if (meshLoaded) {
  74996. meshLoaded(_this._defaultModel);
  74997. }
  74998. });
  74999. };
  75000. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  75001. /**
  75002. * Fired when the A button on this controller is modified
  75003. */
  75004. get: function () {
  75005. if (this.hand === 'right') {
  75006. return this.onMainButtonStateChangedObservable;
  75007. }
  75008. else {
  75009. throw new Error('No A button on left hand');
  75010. }
  75011. },
  75012. enumerable: true,
  75013. configurable: true
  75014. });
  75015. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  75016. /**
  75017. * Fired when the B button on this controller is modified
  75018. */
  75019. get: function () {
  75020. if (this.hand === 'right') {
  75021. return this.onSecondaryButtonStateChangedObservable;
  75022. }
  75023. else {
  75024. throw new Error('No B button on left hand');
  75025. }
  75026. },
  75027. enumerable: true,
  75028. configurable: true
  75029. });
  75030. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  75031. /**
  75032. * Fired when the X button on this controller is modified
  75033. */
  75034. get: function () {
  75035. if (this.hand === 'left') {
  75036. return this.onMainButtonStateChangedObservable;
  75037. }
  75038. else {
  75039. throw new Error('No X button on right hand');
  75040. }
  75041. },
  75042. enumerable: true,
  75043. configurable: true
  75044. });
  75045. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  75046. /**
  75047. * Fired when the Y button on this controller is modified
  75048. */
  75049. get: function () {
  75050. if (this.hand === 'left') {
  75051. return this.onSecondaryButtonStateChangedObservable;
  75052. }
  75053. else {
  75054. throw new Error('No Y button on right hand');
  75055. }
  75056. },
  75057. enumerable: true,
  75058. configurable: true
  75059. });
  75060. /**
  75061. * Called once for each button that changed state since the last frame
  75062. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  75063. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  75064. * 2) secondary trigger (same)
  75065. * 3) A (right) X (left), touch, pressed = value
  75066. * 4) B / Y
  75067. * 5) thumb rest
  75068. * @param buttonIdx Which button index changed
  75069. * @param state New state of the button
  75070. * @param changes Which properties on the state changed since last frame
  75071. */
  75072. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75073. var notifyObject = state; //{ state: state, changes: changes };
  75074. var triggerDirection = this.hand === 'right' ? -1 : 1;
  75075. switch (buttonIdx) {
  75076. case 0:
  75077. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  75078. return;
  75079. case 1: // index trigger
  75080. if (this._defaultModel) {
  75081. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  75082. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  75083. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  75084. }
  75085. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  75086. return;
  75087. case 2: // secondary trigger
  75088. if (this._defaultModel) {
  75089. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  75090. }
  75091. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  75092. return;
  75093. case 3:
  75094. if (this._defaultModel) {
  75095. if (notifyObject.pressed) {
  75096. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  75097. }
  75098. else {
  75099. (this._defaultModel.getChildren()[1]).position.y = 0;
  75100. }
  75101. }
  75102. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  75103. return;
  75104. case 4:
  75105. if (this._defaultModel) {
  75106. if (notifyObject.pressed) {
  75107. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  75108. }
  75109. else {
  75110. (this._defaultModel.getChildren()[2]).position.y = 0;
  75111. }
  75112. }
  75113. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  75114. return;
  75115. case 5:
  75116. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  75117. return;
  75118. }
  75119. };
  75120. /**
  75121. * Base Url for the controller model.
  75122. */
  75123. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  75124. /**
  75125. * File name for the left controller model.
  75126. */
  75127. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  75128. /**
  75129. * File name for the right controller model.
  75130. */
  75131. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  75132. return OculusTouchController;
  75133. }(BABYLON.WebVRController));
  75134. BABYLON.OculusTouchController = OculusTouchController;
  75135. })(BABYLON || (BABYLON = {}));
  75136. //# sourceMappingURL=babylon.oculusTouchController.js.map
  75137. var BABYLON;
  75138. (function (BABYLON) {
  75139. /**
  75140. * Vive Controller
  75141. */
  75142. var ViveController = /** @class */ (function (_super) {
  75143. __extends(ViveController, _super);
  75144. /**
  75145. * Creates a new ViveController from a gamepad
  75146. * @param vrGamepad the gamepad that the controller should be created from
  75147. */
  75148. function ViveController(vrGamepad) {
  75149. var _this = _super.call(this, vrGamepad) || this;
  75150. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  75151. _this._invertLeftStickY = true;
  75152. return _this;
  75153. }
  75154. /**
  75155. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75156. * @param scene scene in which to add meshes
  75157. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75158. */
  75159. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75160. var _this = this;
  75161. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  75162. /*
  75163. Parent Mesh name: ViveWand
  75164. - body
  75165. - r_gripper
  75166. - l_gripper
  75167. - menu_button
  75168. - system_button
  75169. - trackpad
  75170. - trigger
  75171. - LED
  75172. */
  75173. _this._defaultModel = newMeshes[1];
  75174. _this.attachToMesh(_this._defaultModel);
  75175. if (meshLoaded) {
  75176. meshLoaded(_this._defaultModel);
  75177. }
  75178. });
  75179. };
  75180. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  75181. /**
  75182. * Fired when the left button on this controller is modified
  75183. */
  75184. get: function () {
  75185. return this.onMainButtonStateChangedObservable;
  75186. },
  75187. enumerable: true,
  75188. configurable: true
  75189. });
  75190. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  75191. /**
  75192. * Fired when the right button on this controller is modified
  75193. */
  75194. get: function () {
  75195. return this.onMainButtonStateChangedObservable;
  75196. },
  75197. enumerable: true,
  75198. configurable: true
  75199. });
  75200. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  75201. /**
  75202. * Fired when the menu button on this controller is modified
  75203. */
  75204. get: function () {
  75205. return this.onSecondaryButtonStateChangedObservable;
  75206. },
  75207. enumerable: true,
  75208. configurable: true
  75209. });
  75210. /**
  75211. * Called once for each button that changed state since the last frame
  75212. * Vive mapping:
  75213. * 0: touchpad
  75214. * 1: trigger
  75215. * 2: left AND right buttons
  75216. * 3: menu button
  75217. * @param buttonIdx Which button index changed
  75218. * @param state New state of the button
  75219. * @param changes Which properties on the state changed since last frame
  75220. */
  75221. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75222. var notifyObject = state; //{ state: state, changes: changes };
  75223. switch (buttonIdx) {
  75224. case 0:
  75225. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  75226. return;
  75227. case 1: // index trigger
  75228. if (this._defaultModel) {
  75229. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  75230. }
  75231. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  75232. return;
  75233. case 2: // left AND right button
  75234. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  75235. return;
  75236. case 3:
  75237. if (this._defaultModel) {
  75238. if (notifyObject.pressed) {
  75239. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  75240. }
  75241. else {
  75242. (this._defaultModel.getChildren()[2]).position.y = 0;
  75243. }
  75244. }
  75245. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  75246. return;
  75247. }
  75248. };
  75249. /**
  75250. * Base Url for the controller model.
  75251. */
  75252. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  75253. /**
  75254. * File name for the controller model.
  75255. */
  75256. ViveController.MODEL_FILENAME = 'wand.babylon';
  75257. return ViveController;
  75258. }(BABYLON.WebVRController));
  75259. BABYLON.ViveController = ViveController;
  75260. })(BABYLON || (BABYLON = {}));
  75261. //# sourceMappingURL=babylon.viveController.js.map
  75262. var BABYLON;
  75263. (function (BABYLON) {
  75264. /**
  75265. * Generic Controller
  75266. */
  75267. var GenericController = /** @class */ (function (_super) {
  75268. __extends(GenericController, _super);
  75269. /**
  75270. * Creates a new GenericController from a gamepad
  75271. * @param vrGamepad the gamepad that the controller should be created from
  75272. */
  75273. function GenericController(vrGamepad) {
  75274. return _super.call(this, vrGamepad) || this;
  75275. }
  75276. /**
  75277. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75278. * @param scene scene in which to add meshes
  75279. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75280. */
  75281. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75282. var _this = this;
  75283. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  75284. _this._defaultModel = newMeshes[1];
  75285. _this.attachToMesh(_this._defaultModel);
  75286. if (meshLoaded) {
  75287. meshLoaded(_this._defaultModel);
  75288. }
  75289. });
  75290. };
  75291. /**
  75292. * Called once for each button that changed state since the last frame
  75293. * @param buttonIdx Which button index changed
  75294. * @param state New state of the button
  75295. * @param changes Which properties on the state changed since last frame
  75296. */
  75297. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75298. console.log("Button id: " + buttonIdx + "state: ");
  75299. console.dir(state);
  75300. };
  75301. /**
  75302. * Base Url for the controller model.
  75303. */
  75304. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  75305. /**
  75306. * File name for the controller model.
  75307. */
  75308. GenericController.MODEL_FILENAME = 'generic.babylon';
  75309. return GenericController;
  75310. }(BABYLON.WebVRController));
  75311. BABYLON.GenericController = GenericController;
  75312. })(BABYLON || (BABYLON = {}));
  75313. //# sourceMappingURL=babylon.genericController.js.map
  75314. var BABYLON;
  75315. (function (BABYLON) {
  75316. /**
  75317. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  75318. */
  75319. var LoadedMeshInfo = /** @class */ (function () {
  75320. function LoadedMeshInfo() {
  75321. /**
  75322. * Map of the button meshes contained in the controller
  75323. */
  75324. this.buttonMeshes = {};
  75325. /**
  75326. * Map of the axis meshes contained in the controller
  75327. */
  75328. this.axisMeshes = {};
  75329. }
  75330. return LoadedMeshInfo;
  75331. }());
  75332. /**
  75333. * Defines the WindowsMotionController object that the state of the windows motion controller
  75334. */
  75335. var WindowsMotionController = /** @class */ (function (_super) {
  75336. __extends(WindowsMotionController, _super);
  75337. /**
  75338. * Creates a new WindowsMotionController from a gamepad
  75339. * @param vrGamepad the gamepad that the controller should be created from
  75340. */
  75341. function WindowsMotionController(vrGamepad) {
  75342. var _this = _super.call(this, vrGamepad) || this;
  75343. _this._mapping = {
  75344. // Semantic button names
  75345. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  75346. // A mapping of the button name to glTF model node name
  75347. // that should be transformed by button value.
  75348. buttonMeshNames: {
  75349. 'trigger': 'SELECT',
  75350. 'menu': 'MENU',
  75351. 'grip': 'GRASP',
  75352. 'thumbstick': 'THUMBSTICK_PRESS',
  75353. 'trackpad': 'TOUCHPAD_PRESS'
  75354. },
  75355. // This mapping is used to translate from the Motion Controller to Babylon semantics
  75356. buttonObservableNames: {
  75357. 'trigger': 'onTriggerStateChangedObservable',
  75358. 'menu': 'onSecondaryButtonStateChangedObservable',
  75359. 'grip': 'onMainButtonStateChangedObservable',
  75360. 'thumbstick': 'onPadStateChangedObservable',
  75361. 'trackpad': 'onTrackpadChangedObservable'
  75362. },
  75363. // A mapping of the axis name to glTF model node name
  75364. // that should be transformed by axis value.
  75365. // This array mirrors the browserGamepad.axes array, such that
  75366. // the mesh corresponding to axis 0 is in this array index 0.
  75367. axisMeshNames: [
  75368. 'THUMBSTICK_X',
  75369. 'THUMBSTICK_Y',
  75370. 'TOUCHPAD_TOUCH_X',
  75371. 'TOUCHPAD_TOUCH_Y'
  75372. ],
  75373. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  75374. };
  75375. /**
  75376. * Fired when the trackpad on this controller is clicked
  75377. */
  75378. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  75379. /**
  75380. * Fired when the trackpad on this controller is modified
  75381. */
  75382. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  75383. /**
  75384. * The current x and y values of this controller's trackpad
  75385. */
  75386. _this.trackpad = { x: 0, y: 0 };
  75387. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  75388. _this._loadedMeshInfo = null;
  75389. return _this;
  75390. }
  75391. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  75392. /**
  75393. * Fired when the trigger on this controller is modified
  75394. */
  75395. get: function () {
  75396. return this.onTriggerStateChangedObservable;
  75397. },
  75398. enumerable: true,
  75399. configurable: true
  75400. });
  75401. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  75402. /**
  75403. * Fired when the menu button on this controller is modified
  75404. */
  75405. get: function () {
  75406. return this.onSecondaryButtonStateChangedObservable;
  75407. },
  75408. enumerable: true,
  75409. configurable: true
  75410. });
  75411. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  75412. /**
  75413. * Fired when the grip button on this controller is modified
  75414. */
  75415. get: function () {
  75416. return this.onMainButtonStateChangedObservable;
  75417. },
  75418. enumerable: true,
  75419. configurable: true
  75420. });
  75421. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  75422. /**
  75423. * Fired when the thumbstick button on this controller is modified
  75424. */
  75425. get: function () {
  75426. return this.onPadStateChangedObservable;
  75427. },
  75428. enumerable: true,
  75429. configurable: true
  75430. });
  75431. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  75432. /**
  75433. * Fired when the touchpad button on this controller is modified
  75434. */
  75435. get: function () {
  75436. return this.onTrackpadChangedObservable;
  75437. },
  75438. enumerable: true,
  75439. configurable: true
  75440. });
  75441. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  75442. /**
  75443. * Fired when the touchpad values on this controller are modified
  75444. */
  75445. get: function () {
  75446. return this.onTrackpadValuesChangedObservable;
  75447. },
  75448. enumerable: true,
  75449. configurable: true
  75450. });
  75451. WindowsMotionController.prototype._updateTrackpad = function () {
  75452. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  75453. this.trackpad.x = this.browserGamepad["axes"][2];
  75454. this.trackpad.y = this.browserGamepad["axes"][3];
  75455. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  75456. }
  75457. };
  75458. /**
  75459. * Called once per frame by the engine.
  75460. */
  75461. WindowsMotionController.prototype.update = function () {
  75462. _super.prototype.update.call(this);
  75463. if (this.browserGamepad.axes) {
  75464. this._updateTrackpad();
  75465. // Only need to animate axes if there is a loaded mesh
  75466. if (this._loadedMeshInfo) {
  75467. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  75468. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  75469. }
  75470. }
  75471. }
  75472. };
  75473. /**
  75474. * Called once for each button that changed state since the last frame
  75475. * @param buttonIdx Which button index changed
  75476. * @param state New state of the button
  75477. * @param changes Which properties on the state changed since last frame
  75478. */
  75479. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75480. var buttonName = this._mapping.buttons[buttonIdx];
  75481. if (!buttonName) {
  75482. return;
  75483. }
  75484. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  75485. this._updateTrackpad();
  75486. // Only emit events for buttons that we know how to map from index to name
  75487. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  75488. if (observable) {
  75489. observable.notifyObservers(state);
  75490. }
  75491. this._lerpButtonTransform(buttonName, state.value);
  75492. };
  75493. /**
  75494. * Moves the buttons on the controller mesh based on their current state
  75495. * @param buttonName the name of the button to move
  75496. * @param buttonValue the value of the button which determines the buttons new position
  75497. */
  75498. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  75499. // If there is no loaded mesh, there is nothing to transform.
  75500. if (!this._loadedMeshInfo) {
  75501. return;
  75502. }
  75503. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  75504. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  75505. return;
  75506. }
  75507. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  75508. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  75509. };
  75510. /**
  75511. * Moves the axis on the controller mesh based on its current state
  75512. * @param axis the index of the axis
  75513. * @param axisValue the value of the axis which determines the meshes new position
  75514. * @hidden
  75515. */
  75516. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  75517. if (!this._loadedMeshInfo) {
  75518. return;
  75519. }
  75520. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  75521. if (!meshInfo) {
  75522. return;
  75523. }
  75524. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  75525. return;
  75526. }
  75527. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  75528. var lerpValue = axisValue * 0.5 + 0.5;
  75529. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  75530. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  75531. };
  75532. /**
  75533. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75534. * @param scene scene in which to add meshes
  75535. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75536. */
  75537. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  75538. var _this = this;
  75539. if (forceDefault === void 0) { forceDefault = false; }
  75540. var path;
  75541. var filename;
  75542. // Checking if GLB loader is present
  75543. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  75544. // Determine the device specific folder based on the ID suffix
  75545. var device = 'default';
  75546. if (this.id && !forceDefault) {
  75547. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  75548. device = ((match && match[0]) || device);
  75549. }
  75550. // Hand
  75551. if (this.hand === 'left') {
  75552. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  75553. }
  75554. else { // Right is the default if no hand is specified
  75555. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  75556. }
  75557. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  75558. }
  75559. else {
  75560. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  75561. path = BABYLON.GenericController.MODEL_BASE_URL;
  75562. filename = BABYLON.GenericController.MODEL_FILENAME;
  75563. }
  75564. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  75565. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  75566. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  75567. if (!_this._loadedMeshInfo) {
  75568. return;
  75569. }
  75570. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  75571. _this.attachToMesh(_this._defaultModel);
  75572. if (meshLoaded) {
  75573. meshLoaded(_this._defaultModel);
  75574. }
  75575. }, null, function (scene, message) {
  75576. BABYLON.Tools.Log(message);
  75577. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  75578. if (!forceDefault) {
  75579. _this.initControllerMesh(scene, meshLoaded, true);
  75580. }
  75581. });
  75582. };
  75583. /**
  75584. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  75585. * can be transformed by button presses and axes values, based on this._mapping.
  75586. *
  75587. * @param scene scene in which the meshes exist
  75588. * @param meshes list of meshes that make up the controller model to process
  75589. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  75590. */
  75591. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  75592. var loadedMeshInfo = null;
  75593. // Create a new mesh to contain the glTF hierarchy
  75594. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  75595. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  75596. var childMesh = null;
  75597. for (var i = 0; i < meshes.length; i++) {
  75598. var mesh = meshes[i];
  75599. if (!mesh.parent) {
  75600. // Exclude controller meshes from picking results
  75601. mesh.isPickable = false;
  75602. // Handle root node, attach to the new parentMesh
  75603. childMesh = mesh;
  75604. break;
  75605. }
  75606. }
  75607. if (childMesh) {
  75608. childMesh.setParent(parentMesh);
  75609. // Create our mesh info. Note that this method will always return non-null.
  75610. loadedMeshInfo = this.createMeshInfo(parentMesh);
  75611. }
  75612. else {
  75613. BABYLON.Tools.Warn('Could not find root node in model file.');
  75614. }
  75615. return loadedMeshInfo;
  75616. };
  75617. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  75618. var loadedMeshInfo = new LoadedMeshInfo();
  75619. var i;
  75620. loadedMeshInfo.rootNode = rootNode;
  75621. // Reset the caches
  75622. loadedMeshInfo.buttonMeshes = {};
  75623. loadedMeshInfo.axisMeshes = {};
  75624. // Button Meshes
  75625. for (i = 0; i < this._mapping.buttons.length; i++) {
  75626. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  75627. if (!buttonMeshName) {
  75628. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  75629. continue;
  75630. }
  75631. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  75632. if (!buttonMesh) {
  75633. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  75634. continue;
  75635. }
  75636. var buttonMeshInfo = {
  75637. index: i,
  75638. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  75639. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  75640. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  75641. };
  75642. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  75643. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  75644. }
  75645. else {
  75646. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  75647. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  75648. '(VALUE: ' + !!buttonMeshInfo.value +
  75649. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  75650. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  75651. ')');
  75652. }
  75653. }
  75654. // Axis Meshes
  75655. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  75656. var axisMeshName = this._mapping.axisMeshNames[i];
  75657. if (!axisMeshName) {
  75658. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  75659. continue;
  75660. }
  75661. var axisMesh = getChildByName(rootNode, axisMeshName);
  75662. if (!axisMesh) {
  75663. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  75664. continue;
  75665. }
  75666. var axisMeshInfo = {
  75667. index: i,
  75668. value: getImmediateChildByName(axisMesh, 'VALUE'),
  75669. min: getImmediateChildByName(axisMesh, 'MIN'),
  75670. max: getImmediateChildByName(axisMesh, 'MAX')
  75671. };
  75672. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  75673. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  75674. }
  75675. else {
  75676. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  75677. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  75678. '(VALUE: ' + !!axisMeshInfo.value +
  75679. ', MIN: ' + !!axisMeshInfo.min +
  75680. ', MAX:' + !!axisMeshInfo.max +
  75681. ')');
  75682. }
  75683. }
  75684. // Pointing Ray
  75685. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  75686. if (!loadedMeshInfo.pointingPoseNode) {
  75687. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  75688. }
  75689. else {
  75690. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  75691. }
  75692. return loadedMeshInfo;
  75693. // Look through all children recursively. This will return null if no mesh exists with the given name.
  75694. function getChildByName(node, name) {
  75695. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  75696. }
  75697. // Look through only immediate children. This will return null if no mesh exists with the given name.
  75698. function getImmediateChildByName(node, name) {
  75699. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  75700. }
  75701. };
  75702. /**
  75703. * Gets the ray of the controller in the direction the controller is pointing
  75704. * @param length the length the resulting ray should be
  75705. * @returns a ray in the direction the controller is pointing
  75706. */
  75707. WindowsMotionController.prototype.getForwardRay = function (length) {
  75708. if (length === void 0) { length = 100; }
  75709. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  75710. return _super.prototype.getForwardRay.call(this, length);
  75711. }
  75712. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  75713. var origin = m.getTranslation();
  75714. var forward = new BABYLON.Vector3(0, 0, -1);
  75715. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  75716. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  75717. return new BABYLON.Ray(origin, direction, length);
  75718. };
  75719. /**
  75720. * Disposes of the controller
  75721. */
  75722. WindowsMotionController.prototype.dispose = function () {
  75723. _super.prototype.dispose.call(this);
  75724. this.onTrackpadChangedObservable.clear();
  75725. };
  75726. /**
  75727. * The base url used to load the left and right controller models
  75728. */
  75729. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  75730. /**
  75731. * The name of the left controller model file
  75732. */
  75733. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  75734. /**
  75735. * The name of the right controller model file
  75736. */
  75737. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  75738. /**
  75739. * The controller name prefix for this controller type
  75740. */
  75741. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  75742. /**
  75743. * The controller id pattern for this controller type
  75744. */
  75745. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  75746. return WindowsMotionController;
  75747. }(BABYLON.WebVRController));
  75748. BABYLON.WindowsMotionController = WindowsMotionController;
  75749. })(BABYLON || (BABYLON = {}));
  75750. //# sourceMappingURL=babylon.windowsMotionController.js.map
  75751. var BABYLON;
  75752. (function (BABYLON) {
  75753. /**
  75754. * Gear VR Controller
  75755. */
  75756. var GearVRController = /** @class */ (function (_super) {
  75757. __extends(GearVRController, _super);
  75758. /**
  75759. * Creates a new GearVRController from a gamepad
  75760. * @param vrGamepad the gamepad that the controller should be created from
  75761. */
  75762. function GearVRController(vrGamepad) {
  75763. var _this = _super.call(this, vrGamepad) || this;
  75764. _this._maxRotationDistFromHeadset = Math.PI / 5;
  75765. _this._draggedRoomRotation = 0;
  75766. _this._tmpVector = new BABYLON.Vector3();
  75767. _this._buttonIndexToObservableNameMap = [
  75768. 'onTrackpadChangedObservable',
  75769. 'onTriggerStateChangedObservable' // Trigger
  75770. ];
  75771. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  75772. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  75773. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  75774. return _this;
  75775. }
  75776. /**
  75777. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  75778. * @param poseData raw pose fromthe device
  75779. */
  75780. GearVRController.prototype.updateFromDevice = function (poseData) {
  75781. _super.prototype.updateFromDevice.call(this, poseData);
  75782. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  75783. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  75784. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  75785. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  75786. // Find the radian distance away that the headset is from the controllers rotation
  75787. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  75788. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  75789. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  75790. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  75791. this._draggedRoomRotation += rotationAmount;
  75792. // Rotate controller around headset
  75793. var sin = Math.sin(-rotationAmount);
  75794. var cos = Math.cos(-rotationAmount);
  75795. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  75796. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  75797. }
  75798. }
  75799. }
  75800. };
  75801. /**
  75802. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75803. * @param scene scene in which to add meshes
  75804. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75805. */
  75806. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75807. var _this = this;
  75808. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  75809. // Offset the controller so it will rotate around the users wrist
  75810. var mesh = new BABYLON.Mesh("", scene);
  75811. newMeshes[1].parent = mesh;
  75812. newMeshes[1].position.z = -0.15;
  75813. _this._defaultModel = mesh;
  75814. _this.attachToMesh(_this._defaultModel);
  75815. if (meshLoaded) {
  75816. meshLoaded(_this._defaultModel);
  75817. }
  75818. });
  75819. };
  75820. /**
  75821. * Called once for each button that changed state since the last frame
  75822. * @param buttonIdx Which button index changed
  75823. * @param state New state of the button
  75824. * @param changes Which properties on the state changed since last frame
  75825. */
  75826. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75827. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  75828. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  75829. // Only emit events for buttons that we know how to map from index to observable
  75830. var observable = this[observableName];
  75831. if (observable) {
  75832. observable.notifyObservers(state);
  75833. }
  75834. }
  75835. };
  75836. /**
  75837. * Base Url for the controller model.
  75838. */
  75839. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  75840. /**
  75841. * File name for the controller model.
  75842. */
  75843. GearVRController.MODEL_FILENAME = 'generic.babylon';
  75844. /**
  75845. * Gamepad Id prefix used to identify this controller.
  75846. */
  75847. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  75848. return GearVRController;
  75849. }(BABYLON.WebVRController));
  75850. BABYLON.GearVRController = GearVRController;
  75851. })(BABYLON || (BABYLON = {}));
  75852. //# sourceMappingURL=babylon.gearVRController.js.map
  75853. var BABYLON;
  75854. (function (BABYLON) {
  75855. /**
  75856. * Google Daydream controller
  75857. */
  75858. var DaydreamController = /** @class */ (function (_super) {
  75859. __extends(DaydreamController, _super);
  75860. /**
  75861. * Creates a new DaydreamController from a gamepad
  75862. * @param vrGamepad the gamepad that the controller should be created from
  75863. */
  75864. function DaydreamController(vrGamepad) {
  75865. var _this = _super.call(this, vrGamepad) || this;
  75866. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  75867. return _this;
  75868. }
  75869. /**
  75870. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75871. * @param scene scene in which to add meshes
  75872. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75873. */
  75874. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75875. var _this = this;
  75876. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  75877. _this._defaultModel = newMeshes[1];
  75878. _this.attachToMesh(_this._defaultModel);
  75879. if (meshLoaded) {
  75880. meshLoaded(_this._defaultModel);
  75881. }
  75882. });
  75883. };
  75884. /**
  75885. * Called once for each button that changed state since the last frame
  75886. * @param buttonIdx Which button index changed
  75887. * @param state New state of the button
  75888. * @param changes Which properties on the state changed since last frame
  75889. */
  75890. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75891. // Daydream controller only has 1 GamepadButton (on the trackpad).
  75892. if (buttonIdx === 0) {
  75893. var observable = this.onTriggerStateChangedObservable;
  75894. if (observable) {
  75895. observable.notifyObservers(state);
  75896. }
  75897. }
  75898. else {
  75899. // If the app or home buttons are ever made available
  75900. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  75901. }
  75902. };
  75903. /**
  75904. * Base Url for the controller model.
  75905. */
  75906. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  75907. /**
  75908. * File name for the controller model.
  75909. */
  75910. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  75911. /**
  75912. * Gamepad Id prefix used to identify Daydream Controller.
  75913. */
  75914. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  75915. return DaydreamController;
  75916. }(BABYLON.WebVRController));
  75917. BABYLON.DaydreamController = DaydreamController;
  75918. })(BABYLON || (BABYLON = {}));
  75919. //# sourceMappingURL=babylon.daydreamController.js.map
  75920. var BABYLON;
  75921. (function (BABYLON) {
  75922. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  75923. get: function () {
  75924. if (!this._gamepadManager) {
  75925. this._gamepadManager = new BABYLON.GamepadManager(this);
  75926. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  75927. if (!component) {
  75928. component = new GamepadSystemSceneComponent(this);
  75929. this._addComponent(component);
  75930. }
  75931. }
  75932. return this._gamepadManager;
  75933. },
  75934. enumerable: true,
  75935. configurable: true
  75936. });
  75937. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  75938. this.add(new BABYLON.FreeCameraGamepadInput());
  75939. return this;
  75940. };
  75941. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  75942. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  75943. return this;
  75944. };
  75945. /**
  75946. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  75947. */
  75948. var GamepadSystemSceneComponent = /** @class */ (function () {
  75949. /**
  75950. * Creates a new instance of the component for the given scene
  75951. * @param scene Defines the scene to register the component in
  75952. */
  75953. function GamepadSystemSceneComponent(scene) {
  75954. /**
  75955. * The component name helpfull to identify the component in the list of scene components.
  75956. */
  75957. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  75958. this.scene = scene;
  75959. }
  75960. /**
  75961. * Registers the component in a given scene
  75962. */
  75963. GamepadSystemSceneComponent.prototype.register = function () {
  75964. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  75965. };
  75966. /**
  75967. * Rebuilds the elements related to this component in case of
  75968. * context lost for instance.
  75969. */
  75970. GamepadSystemSceneComponent.prototype.rebuild = function () {
  75971. // Nothing to do for gamepads
  75972. };
  75973. /**
  75974. * Disposes the component and the associated ressources
  75975. */
  75976. GamepadSystemSceneComponent.prototype.dispose = function () {
  75977. var gamepadManager = this.scene._gamepadManager;
  75978. if (gamepadManager) {
  75979. gamepadManager.dispose();
  75980. this.scene._gamepadManager = null;
  75981. }
  75982. };
  75983. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  75984. var gamepadManager = this.scene._gamepadManager;
  75985. if (gamepadManager && gamepadManager._isMonitoring) {
  75986. gamepadManager._checkGamepadsStatus();
  75987. }
  75988. };
  75989. return GamepadSystemSceneComponent;
  75990. }());
  75991. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  75992. })(BABYLON || (BABYLON = {}));
  75993. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  75994. var BABYLON;
  75995. (function (BABYLON) {
  75996. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  75997. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  75998. });
  75999. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  76000. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  76001. });
  76002. var FollowCamera = /** @class */ (function (_super) {
  76003. __extends(FollowCamera, _super);
  76004. function FollowCamera(name, position, scene, lockedTarget) {
  76005. if (lockedTarget === void 0) { lockedTarget = null; }
  76006. var _this = _super.call(this, name, position, scene) || this;
  76007. _this.radius = 12;
  76008. _this.rotationOffset = 0;
  76009. _this.heightOffset = 4;
  76010. _this.cameraAcceleration = 0.05;
  76011. _this.maxCameraSpeed = 20;
  76012. _this.lockedTarget = lockedTarget;
  76013. return _this;
  76014. }
  76015. FollowCamera.prototype.getRadians = function (degrees) {
  76016. return degrees * Math.PI / 180;
  76017. };
  76018. FollowCamera.prototype.follow = function (cameraTarget) {
  76019. if (!cameraTarget)
  76020. return;
  76021. var yRotation;
  76022. if (cameraTarget.rotationQuaternion) {
  76023. var rotMatrix = new BABYLON.Matrix();
  76024. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  76025. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  76026. }
  76027. else {
  76028. yRotation = cameraTarget.rotation.y;
  76029. }
  76030. var radians = this.getRadians(this.rotationOffset) + yRotation;
  76031. var targetPosition = cameraTarget.getAbsolutePosition();
  76032. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  76033. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  76034. var dx = targetX - this.position.x;
  76035. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  76036. var dz = (targetZ) - this.position.z;
  76037. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  76038. var vy = dy * this.cameraAcceleration;
  76039. var vz = dz * this.cameraAcceleration * 2;
  76040. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  76041. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  76042. }
  76043. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  76044. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  76045. }
  76046. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  76047. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  76048. }
  76049. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  76050. this.setTarget(targetPosition);
  76051. };
  76052. /** @hidden */
  76053. FollowCamera.prototype._checkInputs = function () {
  76054. _super.prototype._checkInputs.call(this);
  76055. if (this.lockedTarget) {
  76056. this.follow(this.lockedTarget);
  76057. }
  76058. };
  76059. FollowCamera.prototype.getClassName = function () {
  76060. return "FollowCamera";
  76061. };
  76062. __decorate([
  76063. BABYLON.serialize()
  76064. ], FollowCamera.prototype, "radius", void 0);
  76065. __decorate([
  76066. BABYLON.serialize()
  76067. ], FollowCamera.prototype, "rotationOffset", void 0);
  76068. __decorate([
  76069. BABYLON.serialize()
  76070. ], FollowCamera.prototype, "heightOffset", void 0);
  76071. __decorate([
  76072. BABYLON.serialize()
  76073. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  76074. __decorate([
  76075. BABYLON.serialize()
  76076. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  76077. __decorate([
  76078. BABYLON.serializeAsMeshReference("lockedTargetId")
  76079. ], FollowCamera.prototype, "lockedTarget", void 0);
  76080. return FollowCamera;
  76081. }(BABYLON.TargetCamera));
  76082. BABYLON.FollowCamera = FollowCamera;
  76083. var ArcFollowCamera = /** @class */ (function (_super) {
  76084. __extends(ArcFollowCamera, _super);
  76085. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  76086. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  76087. _this.alpha = alpha;
  76088. _this.beta = beta;
  76089. _this.radius = radius;
  76090. _this.target = target;
  76091. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  76092. _this.follow();
  76093. return _this;
  76094. }
  76095. ArcFollowCamera.prototype.follow = function () {
  76096. if (!this.target) {
  76097. return;
  76098. }
  76099. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  76100. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  76101. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  76102. var targetPosition = this.target.getAbsolutePosition();
  76103. this.position = targetPosition.add(this._cartesianCoordinates);
  76104. this.setTarget(targetPosition);
  76105. };
  76106. /** @hidden */
  76107. ArcFollowCamera.prototype._checkInputs = function () {
  76108. _super.prototype._checkInputs.call(this);
  76109. this.follow();
  76110. };
  76111. ArcFollowCamera.prototype.getClassName = function () {
  76112. return "ArcFollowCamera";
  76113. };
  76114. return ArcFollowCamera;
  76115. }(BABYLON.TargetCamera));
  76116. BABYLON.ArcFollowCamera = ArcFollowCamera;
  76117. })(BABYLON || (BABYLON = {}));
  76118. //# sourceMappingURL=babylon.followCamera.js.map
  76119. var BABYLON;
  76120. (function (BABYLON) {
  76121. // We're mainly based on the logic defined into the FreeCamera code
  76122. var UniversalCamera = /** @class */ (function (_super) {
  76123. __extends(UniversalCamera, _super);
  76124. //-- end properties for backward compatibility for inputs
  76125. function UniversalCamera(name, position, scene) {
  76126. var _this = _super.call(this, name, position, scene) || this;
  76127. _this.inputs.addGamepad();
  76128. return _this;
  76129. }
  76130. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  76131. //-- Begin properties for backward compatibility for inputs
  76132. get: function () {
  76133. var gamepad = this.inputs.attached["gamepad"];
  76134. if (gamepad)
  76135. return gamepad.gamepadAngularSensibility;
  76136. return 0;
  76137. },
  76138. set: function (value) {
  76139. var gamepad = this.inputs.attached["gamepad"];
  76140. if (gamepad)
  76141. gamepad.gamepadAngularSensibility = value;
  76142. },
  76143. enumerable: true,
  76144. configurable: true
  76145. });
  76146. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  76147. get: function () {
  76148. var gamepad = this.inputs.attached["gamepad"];
  76149. if (gamepad)
  76150. return gamepad.gamepadMoveSensibility;
  76151. return 0;
  76152. },
  76153. set: function (value) {
  76154. var gamepad = this.inputs.attached["gamepad"];
  76155. if (gamepad)
  76156. gamepad.gamepadMoveSensibility = value;
  76157. },
  76158. enumerable: true,
  76159. configurable: true
  76160. });
  76161. UniversalCamera.prototype.getClassName = function () {
  76162. return "UniversalCamera";
  76163. };
  76164. return UniversalCamera;
  76165. }(BABYLON.TouchCamera));
  76166. BABYLON.UniversalCamera = UniversalCamera;
  76167. })(BABYLON || (BABYLON = {}));
  76168. //# sourceMappingURL=babylon.universalCamera.js.map
  76169. var BABYLON;
  76170. (function (BABYLON) {
  76171. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  76172. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  76173. });
  76174. // We're mainly based on the logic defined into the FreeCamera code
  76175. var GamepadCamera = /** @class */ (function (_super) {
  76176. __extends(GamepadCamera, _super);
  76177. //-- end properties for backward compatibility for inputs
  76178. function GamepadCamera(name, position, scene) {
  76179. return _super.call(this, name, position, scene) || this;
  76180. }
  76181. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  76182. //-- Begin properties for backward compatibility for inputs
  76183. get: function () {
  76184. var gamepad = this.inputs.attached["gamepad"];
  76185. if (gamepad)
  76186. return gamepad.gamepadAngularSensibility;
  76187. return 0;
  76188. },
  76189. set: function (value) {
  76190. var gamepad = this.inputs.attached["gamepad"];
  76191. if (gamepad)
  76192. gamepad.gamepadAngularSensibility = value;
  76193. },
  76194. enumerable: true,
  76195. configurable: true
  76196. });
  76197. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  76198. get: function () {
  76199. var gamepad = this.inputs.attached["gamepad"];
  76200. if (gamepad)
  76201. return gamepad.gamepadMoveSensibility;
  76202. return 0;
  76203. },
  76204. set: function (value) {
  76205. var gamepad = this.inputs.attached["gamepad"];
  76206. if (gamepad)
  76207. gamepad.gamepadMoveSensibility = value;
  76208. },
  76209. enumerable: true,
  76210. configurable: true
  76211. });
  76212. GamepadCamera.prototype.getClassName = function () {
  76213. return "GamepadCamera";
  76214. };
  76215. return GamepadCamera;
  76216. }(BABYLON.UniversalCamera));
  76217. BABYLON.GamepadCamera = GamepadCamera;
  76218. })(BABYLON || (BABYLON = {}));
  76219. //# sourceMappingURL=babylon.gamepadCamera.js.map
  76220. var BABYLON;
  76221. (function (BABYLON) {
  76222. var PostProcessRenderPipelineManager = /** @class */ (function () {
  76223. function PostProcessRenderPipelineManager() {
  76224. this._renderPipelines = {};
  76225. }
  76226. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  76227. this._renderPipelines[renderPipeline._name] = renderPipeline;
  76228. };
  76229. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  76230. if (unique === void 0) { unique = false; }
  76231. var renderPipeline = this._renderPipelines[renderPipelineName];
  76232. if (!renderPipeline) {
  76233. return;
  76234. }
  76235. renderPipeline._attachCameras(cameras, unique);
  76236. };
  76237. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  76238. var renderPipeline = this._renderPipelines[renderPipelineName];
  76239. if (!renderPipeline) {
  76240. return;
  76241. }
  76242. renderPipeline._detachCameras(cameras);
  76243. };
  76244. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  76245. var renderPipeline = this._renderPipelines[renderPipelineName];
  76246. if (!renderPipeline) {
  76247. return;
  76248. }
  76249. renderPipeline._enableEffect(renderEffectName, cameras);
  76250. };
  76251. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  76252. var renderPipeline = this._renderPipelines[renderPipelineName];
  76253. if (!renderPipeline) {
  76254. return;
  76255. }
  76256. renderPipeline._disableEffect(renderEffectName, cameras);
  76257. };
  76258. PostProcessRenderPipelineManager.prototype.update = function () {
  76259. for (var renderPipelineName in this._renderPipelines) {
  76260. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  76261. var pipeline = this._renderPipelines[renderPipelineName];
  76262. if (!pipeline.isSupported) {
  76263. pipeline.dispose();
  76264. delete this._renderPipelines[renderPipelineName];
  76265. }
  76266. else {
  76267. pipeline._update();
  76268. }
  76269. }
  76270. }
  76271. };
  76272. /** @hidden */
  76273. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  76274. for (var renderPipelineName in this._renderPipelines) {
  76275. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  76276. var pipeline = this._renderPipelines[renderPipelineName];
  76277. pipeline._rebuild();
  76278. }
  76279. }
  76280. };
  76281. PostProcessRenderPipelineManager.prototype.dispose = function () {
  76282. for (var renderPipelineName in this._renderPipelines) {
  76283. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  76284. var pipeline = this._renderPipelines[renderPipelineName];
  76285. pipeline.dispose();
  76286. }
  76287. }
  76288. };
  76289. return PostProcessRenderPipelineManager;
  76290. }());
  76291. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  76292. })(BABYLON || (BABYLON = {}));
  76293. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  76294. var BABYLON;
  76295. (function (BABYLON) {
  76296. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  76297. get: function () {
  76298. if (!this._postProcessRenderPipelineManager) {
  76299. // Register the G Buffer component to the scene.
  76300. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  76301. if (!component) {
  76302. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  76303. this._addComponent(component);
  76304. }
  76305. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  76306. }
  76307. return this._postProcessRenderPipelineManager;
  76308. },
  76309. enumerable: true,
  76310. configurable: true
  76311. });
  76312. /**
  76313. * Defines the Render Pipeline scene component responsible to rendering pipelines
  76314. */
  76315. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  76316. /**
  76317. * Creates a new instance of the component for the given scene
  76318. * @param scene Defines the scene to register the component in
  76319. */
  76320. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  76321. /**
  76322. * The component name helpfull to identify the component in the list of scene components.
  76323. */
  76324. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  76325. this.scene = scene;
  76326. }
  76327. /**
  76328. * Registers the component in a given scene
  76329. */
  76330. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  76331. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  76332. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_REBUILDGEOMETRY_POSTPROCESSRENDERPIPELINEMANAGER, this, this._rebuildGeometry);
  76333. };
  76334. /**
  76335. * Rebuilds the elements related to this component in case of
  76336. * context lost for instance.
  76337. */
  76338. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  76339. // Nothing to do for this component
  76340. };
  76341. /**
  76342. * Disposes the component and the associated ressources
  76343. */
  76344. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  76345. if (this.scene._postProcessRenderPipelineManager) {
  76346. this.scene._postProcessRenderPipelineManager.dispose();
  76347. }
  76348. };
  76349. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  76350. if (this.scene._postProcessRenderPipelineManager) {
  76351. this.scene._postProcessRenderPipelineManager.update();
  76352. }
  76353. };
  76354. PostProcessRenderPipelineManagerSceneComponent.prototype._rebuildGeometry = function () {
  76355. if (this.scene._postProcessRenderPipelineManager) {
  76356. this.scene._postProcessRenderPipelineManager._rebuild();
  76357. }
  76358. };
  76359. return PostProcessRenderPipelineManagerSceneComponent;
  76360. }());
  76361. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  76362. })(BABYLON || (BABYLON = {}));
  76363. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  76364. var BABYLON;
  76365. (function (BABYLON) {
  76366. /**
  76367. * This represents a set of one or more post processes in Babylon.
  76368. * A post process can be used to apply a shader to a texture after it is rendered.
  76369. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  76370. */
  76371. var PostProcessRenderEffect = /** @class */ (function () {
  76372. /**
  76373. * Instantiates a post process render effect.
  76374. * A post process can be used to apply a shader to a texture after it is rendered.
  76375. * @param engine The engine the effect is tied to
  76376. * @param name The name of the effect
  76377. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  76378. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  76379. */
  76380. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  76381. this._name = name;
  76382. this._singleInstance = singleInstance || true;
  76383. this._getPostProcesses = getPostProcesses;
  76384. this._cameras = {};
  76385. this._indicesForCamera = {};
  76386. this._postProcesses = {};
  76387. }
  76388. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  76389. /**
  76390. * Checks if all the post processes in the effect are supported.
  76391. */
  76392. get: function () {
  76393. for (var index in this._postProcesses) {
  76394. if (this._postProcesses.hasOwnProperty(index)) {
  76395. var pps = this._postProcesses[index];
  76396. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  76397. if (!pps[ppIndex].isSupported) {
  76398. return false;
  76399. }
  76400. }
  76401. }
  76402. }
  76403. return true;
  76404. },
  76405. enumerable: true,
  76406. configurable: true
  76407. });
  76408. /**
  76409. * Updates the current state of the effect
  76410. * @hidden
  76411. */
  76412. PostProcessRenderEffect.prototype._update = function () {
  76413. };
  76414. /**
  76415. * Attaches the effect on cameras
  76416. * @param cameras The camera to attach to.
  76417. * @hidden
  76418. */
  76419. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  76420. var _this = this;
  76421. var cameraKey;
  76422. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76423. if (!cams) {
  76424. return;
  76425. }
  76426. for (var i = 0; i < cams.length; i++) {
  76427. var camera = cams[i];
  76428. var cameraName = camera.name;
  76429. if (this._singleInstance) {
  76430. cameraKey = 0;
  76431. }
  76432. else {
  76433. cameraKey = cameraName;
  76434. }
  76435. if (!this._postProcesses[cameraKey]) {
  76436. var postProcess = this._getPostProcesses();
  76437. if (postProcess) {
  76438. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  76439. }
  76440. }
  76441. if (!this._indicesForCamera[cameraName]) {
  76442. this._indicesForCamera[cameraName] = [];
  76443. }
  76444. this._postProcesses[cameraKey].forEach(function (postProcess) {
  76445. var index = camera.attachPostProcess(postProcess);
  76446. _this._indicesForCamera[cameraName].push(index);
  76447. });
  76448. if (!this._cameras[cameraName]) {
  76449. this._cameras[cameraName] = camera;
  76450. }
  76451. }
  76452. };
  76453. /**
  76454. * Detatches the effect on cameras
  76455. * @param cameras The camera to detatch from.
  76456. * @hidden
  76457. */
  76458. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  76459. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76460. if (!cams) {
  76461. return;
  76462. }
  76463. for (var i = 0; i < cams.length; i++) {
  76464. var camera = cams[i];
  76465. var cameraName = camera.name;
  76466. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  76467. camera.detachPostProcess(postProcess);
  76468. });
  76469. if (this._cameras[cameraName]) {
  76470. //this._indicesForCamera.splice(index, 1);
  76471. this._cameras[cameraName] = null;
  76472. }
  76473. }
  76474. };
  76475. /**
  76476. * Enables the effect on given cameras
  76477. * @param cameras The camera to enable.
  76478. * @hidden
  76479. */
  76480. PostProcessRenderEffect.prototype._enable = function (cameras) {
  76481. var _this = this;
  76482. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76483. if (!cams) {
  76484. return;
  76485. }
  76486. for (var i = 0; i < cams.length; i++) {
  76487. var camera = cams[i];
  76488. var cameraName = camera.name;
  76489. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  76490. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  76491. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  76492. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  76493. });
  76494. }
  76495. }
  76496. }
  76497. };
  76498. /**
  76499. * Disables the effect on the given cameras
  76500. * @param cameras The camera to disable.
  76501. * @hidden
  76502. */
  76503. PostProcessRenderEffect.prototype._disable = function (cameras) {
  76504. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76505. if (!cams) {
  76506. return;
  76507. }
  76508. for (var i = 0; i < cams.length; i++) {
  76509. var camera = cams[i];
  76510. var cameraName = camera.name;
  76511. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  76512. camera.detachPostProcess(postProcess);
  76513. });
  76514. }
  76515. };
  76516. /**
  76517. * Gets a list of the post processes contained in the effect.
  76518. * @param camera The camera to get the post processes on.
  76519. * @returns The list of the post processes in the effect.
  76520. */
  76521. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  76522. if (this._singleInstance) {
  76523. return this._postProcesses[0];
  76524. }
  76525. else {
  76526. if (!camera) {
  76527. return null;
  76528. }
  76529. return this._postProcesses[camera.name];
  76530. }
  76531. };
  76532. return PostProcessRenderEffect;
  76533. }());
  76534. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  76535. })(BABYLON || (BABYLON = {}));
  76536. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  76537. var BABYLON;
  76538. (function (BABYLON) {
  76539. var PostProcessRenderPipeline = /** @class */ (function () {
  76540. function PostProcessRenderPipeline(engine, name) {
  76541. this.engine = engine;
  76542. this._name = name;
  76543. this._renderEffects = {};
  76544. this._renderEffectsForIsolatedPass = new Array();
  76545. this._cameras = [];
  76546. }
  76547. PostProcessRenderPipeline.prototype.getClassName = function () {
  76548. return "PostProcessRenderPipeline";
  76549. };
  76550. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  76551. get: function () {
  76552. for (var renderEffectName in this._renderEffects) {
  76553. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76554. if (!this._renderEffects[renderEffectName].isSupported) {
  76555. return false;
  76556. }
  76557. }
  76558. }
  76559. return true;
  76560. },
  76561. enumerable: true,
  76562. configurable: true
  76563. });
  76564. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  76565. this._renderEffects[renderEffect._name] = renderEffect;
  76566. };
  76567. // private
  76568. /** @hidden */
  76569. PostProcessRenderPipeline.prototype._rebuild = function () {
  76570. };
  76571. /** @hidden */
  76572. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  76573. var renderEffects = this._renderEffects[renderEffectName];
  76574. if (!renderEffects) {
  76575. return;
  76576. }
  76577. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  76578. };
  76579. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  76580. var renderEffects = this._renderEffects[renderEffectName];
  76581. if (!renderEffects) {
  76582. return;
  76583. }
  76584. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  76585. };
  76586. /** @hidden */
  76587. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  76588. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76589. if (!cams) {
  76590. return;
  76591. }
  76592. var indicesToDelete = [];
  76593. var i;
  76594. for (i = 0; i < cams.length; i++) {
  76595. var camera = cams[i];
  76596. var cameraName = camera.name;
  76597. if (this._cameras.indexOf(camera) === -1) {
  76598. this._cameras[cameraName] = camera;
  76599. }
  76600. else if (unique) {
  76601. indicesToDelete.push(i);
  76602. }
  76603. }
  76604. for (i = 0; i < indicesToDelete.length; i++) {
  76605. cameras.splice(indicesToDelete[i], 1);
  76606. }
  76607. for (var renderEffectName in this._renderEffects) {
  76608. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76609. this._renderEffects[renderEffectName]._attachCameras(cams);
  76610. }
  76611. }
  76612. };
  76613. /** @hidden */
  76614. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  76615. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76616. if (!cams) {
  76617. return;
  76618. }
  76619. for (var renderEffectName in this._renderEffects) {
  76620. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76621. this._renderEffects[renderEffectName]._detachCameras(cams);
  76622. }
  76623. }
  76624. for (var i = 0; i < cams.length; i++) {
  76625. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  76626. }
  76627. };
  76628. /** @hidden */
  76629. PostProcessRenderPipeline.prototype._update = function () {
  76630. for (var renderEffectName in this._renderEffects) {
  76631. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76632. this._renderEffects[renderEffectName]._update();
  76633. }
  76634. }
  76635. for (var i = 0; i < this._cameras.length; i++) {
  76636. var cameraName = this._cameras[i].name;
  76637. if (this._renderEffectsForIsolatedPass[cameraName]) {
  76638. this._renderEffectsForIsolatedPass[cameraName]._update();
  76639. }
  76640. }
  76641. };
  76642. /** @hidden */
  76643. PostProcessRenderPipeline.prototype._reset = function () {
  76644. this._renderEffects = {};
  76645. this._renderEffectsForIsolatedPass = new Array();
  76646. };
  76647. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  76648. // 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)
  76649. var effectKeys = Object.keys(this._renderEffects);
  76650. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  76651. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  76652. if (postProcesses) {
  76653. postProcesses[0].samples = sampleCount;
  76654. return true;
  76655. }
  76656. }
  76657. return false;
  76658. };
  76659. PostProcessRenderPipeline.prototype.dispose = function () {
  76660. // Must be implemented by children
  76661. };
  76662. __decorate([
  76663. BABYLON.serialize()
  76664. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  76665. return PostProcessRenderPipeline;
  76666. }());
  76667. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  76668. })(BABYLON || (BABYLON = {}));
  76669. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  76670. var BABYLON;
  76671. (function (BABYLON) {
  76672. /**
  76673. * This represents a depth renderer in Babylon.
  76674. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  76675. */
  76676. var DepthRenderer = /** @class */ (function () {
  76677. /**
  76678. * Instantiates a depth renderer
  76679. * @param scene The scene the renderer belongs to
  76680. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  76681. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  76682. */
  76683. function DepthRenderer(scene, type, camera) {
  76684. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  76685. if (camera === void 0) { camera = null; }
  76686. var _this = this;
  76687. this._scene = scene;
  76688. // Register the G Buffer component to the scene.
  76689. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  76690. if (!component) {
  76691. component = new BABYLON.DepthRendererSceneComponent(scene);
  76692. scene._addComponent(component);
  76693. }
  76694. this._camera = camera;
  76695. var engine = scene.getEngine();
  76696. // Render target
  76697. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  76698. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76699. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76700. this._depthMap.refreshRate = 1;
  76701. this._depthMap.renderParticles = false;
  76702. this._depthMap.renderList = null;
  76703. // Camera to get depth map from to support multiple concurrent cameras
  76704. this._depthMap.activeCamera = this._camera;
  76705. this._depthMap.ignoreCameraViewport = true;
  76706. this._depthMap.useCameraPostProcesses = false;
  76707. // set default depth value to 1.0 (far away)
  76708. this._depthMap.onClearObservable.add(function (engine) {
  76709. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  76710. });
  76711. // Custom render function
  76712. var renderSubMesh = function (subMesh) {
  76713. var mesh = subMesh.getRenderingMesh();
  76714. var scene = _this._scene;
  76715. var engine = scene.getEngine();
  76716. var material = subMesh.getMaterial();
  76717. if (!material) {
  76718. return;
  76719. }
  76720. // Culling and reverse (right handed system)
  76721. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76722. // Managing instances
  76723. var batch = mesh._getInstancesRenderList(subMesh._id);
  76724. if (batch.mustReturn) {
  76725. return;
  76726. }
  76727. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76728. var camera = _this._camera || scene.activeCamera;
  76729. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  76730. engine.enableEffect(_this._effect);
  76731. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76732. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76733. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  76734. // Alpha test
  76735. if (material && material.needAlphaTesting()) {
  76736. var alphaTexture = material.getAlphaTestTexture();
  76737. if (alphaTexture) {
  76738. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76739. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76740. }
  76741. }
  76742. // Bones
  76743. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76744. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76745. }
  76746. // Draw
  76747. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76748. }
  76749. };
  76750. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76751. var index;
  76752. if (depthOnlySubMeshes.length) {
  76753. engine.setColorWrite(false);
  76754. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76755. renderSubMesh(depthOnlySubMeshes.data[index]);
  76756. }
  76757. engine.setColorWrite(true);
  76758. }
  76759. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76760. renderSubMesh(opaqueSubMeshes.data[index]);
  76761. }
  76762. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76763. renderSubMesh(alphaTestSubMeshes.data[index]);
  76764. }
  76765. };
  76766. }
  76767. /**
  76768. * Creates the depth rendering effect and checks if the effect is ready.
  76769. * @param subMesh The submesh to be used to render the depth map of
  76770. * @param useInstances If multiple world instances should be used
  76771. * @returns if the depth renderer is ready to render the depth map
  76772. */
  76773. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  76774. var material = subMesh.getMaterial();
  76775. if (material.disableDepthWrite) {
  76776. return false;
  76777. }
  76778. var defines = [];
  76779. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76780. var mesh = subMesh.getMesh();
  76781. // Alpha test
  76782. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  76783. defines.push("#define ALPHATEST");
  76784. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76785. attribs.push(BABYLON.VertexBuffer.UVKind);
  76786. defines.push("#define UV1");
  76787. }
  76788. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76789. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76790. defines.push("#define UV2");
  76791. }
  76792. }
  76793. // Bones
  76794. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76795. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76796. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76797. if (mesh.numBoneInfluencers > 4) {
  76798. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76799. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76800. }
  76801. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76802. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76803. }
  76804. else {
  76805. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76806. }
  76807. // Instances
  76808. if (useInstances) {
  76809. defines.push("#define INSTANCES");
  76810. attribs.push("world0");
  76811. attribs.push("world1");
  76812. attribs.push("world2");
  76813. attribs.push("world3");
  76814. }
  76815. // Get correct effect
  76816. var join = defines.join("\n");
  76817. if (this._cachedDefines !== join) {
  76818. this._cachedDefines = join;
  76819. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  76820. }
  76821. return this._effect.isReady();
  76822. };
  76823. /**
  76824. * Gets the texture which the depth map will be written to.
  76825. * @returns The depth map texture
  76826. */
  76827. DepthRenderer.prototype.getDepthMap = function () {
  76828. return this._depthMap;
  76829. };
  76830. /**
  76831. * Disposes of the depth renderer.
  76832. */
  76833. DepthRenderer.prototype.dispose = function () {
  76834. this._depthMap.dispose();
  76835. };
  76836. return DepthRenderer;
  76837. }());
  76838. BABYLON.DepthRenderer = DepthRenderer;
  76839. })(BABYLON || (BABYLON = {}));
  76840. //# sourceMappingURL=babylon.depthRenderer.js.map
  76841. var BABYLON;
  76842. (function (BABYLON) {
  76843. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  76844. camera = camera || this.activeCamera;
  76845. if (!camera) {
  76846. throw "No camera available to enable depth renderer";
  76847. }
  76848. if (!this._depthRenderer) {
  76849. this._depthRenderer = {};
  76850. }
  76851. if (!this._depthRenderer[camera.id]) {
  76852. var textureType = 0;
  76853. if (this.getEngine().getCaps().textureHalfFloatRender) {
  76854. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76855. }
  76856. else if (this.getEngine().getCaps().textureFloatRender) {
  76857. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76858. }
  76859. else {
  76860. throw "Depth renderer does not support int texture type";
  76861. }
  76862. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  76863. }
  76864. return this._depthRenderer[camera.id];
  76865. };
  76866. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  76867. camera = camera || this.activeCamera;
  76868. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  76869. return;
  76870. }
  76871. this._depthRenderer[camera.id].dispose();
  76872. delete this._depthRenderer[camera.id];
  76873. };
  76874. /**
  76875. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  76876. * in several rendering techniques.
  76877. */
  76878. var DepthRendererSceneComponent = /** @class */ (function () {
  76879. /**
  76880. * Creates a new instance of the component for the given scene
  76881. * @param scene Defines the scene to register the component in
  76882. */
  76883. function DepthRendererSceneComponent(scene) {
  76884. /**
  76885. * The component name helpfull to identify the component in the list of scene components.
  76886. */
  76887. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  76888. this.scene = scene;
  76889. }
  76890. /**
  76891. * Registers the component in a given scene
  76892. */
  76893. DepthRendererSceneComponent.prototype.register = function () {
  76894. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  76895. };
  76896. /**
  76897. * Rebuilds the elements related to this component in case of
  76898. * context lost for instance.
  76899. */
  76900. DepthRendererSceneComponent.prototype.rebuild = function () {
  76901. // Nothing to do for this component
  76902. };
  76903. /**
  76904. * Disposes the component and the associated ressources
  76905. */
  76906. DepthRendererSceneComponent.prototype.dispose = function () {
  76907. for (var key in this.scene._depthRenderer) {
  76908. this.scene._depthRenderer[key].dispose();
  76909. }
  76910. };
  76911. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  76912. if (this.scene._depthRenderer) {
  76913. for (var key in this.scene._depthRenderer) {
  76914. renderTargets.push(this.scene._depthRenderer[key].getDepthMap());
  76915. }
  76916. }
  76917. };
  76918. return DepthRendererSceneComponent;
  76919. }());
  76920. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  76921. })(BABYLON || (BABYLON = {}));
  76922. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  76923. var BABYLON;
  76924. (function (BABYLON) {
  76925. /**
  76926. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76927. */
  76928. var GeometryBufferRenderer = /** @class */ (function () {
  76929. /**
  76930. * Creates a new G Buffer for the scene
  76931. * @param scene The scene the buffer belongs to
  76932. * @param ratio How big is the buffer related to the main canvas.
  76933. */
  76934. function GeometryBufferRenderer(scene, ratio) {
  76935. if (ratio === void 0) { ratio = 1; }
  76936. this._enablePosition = false;
  76937. this._scene = scene;
  76938. this._ratio = ratio;
  76939. // Register the G Buffer component to the scene.
  76940. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  76941. if (!component) {
  76942. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  76943. scene._addComponent(component);
  76944. }
  76945. // Render target
  76946. this._createRenderTargets();
  76947. }
  76948. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76949. /**
  76950. * Set the render list (meshes to be rendered) used in the G buffer.
  76951. */
  76952. set: function (meshes) {
  76953. this._multiRenderTarget.renderList = meshes;
  76954. },
  76955. enumerable: true,
  76956. configurable: true
  76957. });
  76958. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76959. /**
  76960. * Gets wether or not G buffer are supported by the running hardware.
  76961. * This requires draw buffer supports
  76962. */
  76963. get: function () {
  76964. return this._multiRenderTarget.isSupported;
  76965. },
  76966. enumerable: true,
  76967. configurable: true
  76968. });
  76969. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76970. /**
  76971. * Gets wether or not position are enabled for the G buffer.
  76972. */
  76973. get: function () {
  76974. return this._enablePosition;
  76975. },
  76976. /**
  76977. * Sets wether or not position are enabled for the G buffer.
  76978. */
  76979. set: function (enable) {
  76980. this._enablePosition = enable;
  76981. this.dispose();
  76982. this._createRenderTargets();
  76983. },
  76984. enumerable: true,
  76985. configurable: true
  76986. });
  76987. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76988. /**
  76989. * Gets the scene associated with the buffer.
  76990. */
  76991. get: function () {
  76992. return this._scene;
  76993. },
  76994. enumerable: true,
  76995. configurable: true
  76996. });
  76997. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76998. /**
  76999. * Gets the ratio used by the buffer during its creation.
  77000. * How big is the buffer related to the main canvas.
  77001. */
  77002. get: function () {
  77003. return this._ratio;
  77004. },
  77005. enumerable: true,
  77006. configurable: true
  77007. });
  77008. /**
  77009. * Checks wether everything is ready to render a submesh to the G buffer.
  77010. * @param subMesh the submesh to check readiness for
  77011. * @param useInstances is the mesh drawn using instance or not
  77012. * @returns true if ready otherwise false
  77013. */
  77014. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  77015. var material = subMesh.getMaterial();
  77016. if (material && material.disableDepthWrite) {
  77017. return false;
  77018. }
  77019. var defines = [];
  77020. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  77021. var mesh = subMesh.getMesh();
  77022. // Alpha test
  77023. if (material && material.needAlphaTesting()) {
  77024. defines.push("#define ALPHATEST");
  77025. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77026. attribs.push(BABYLON.VertexBuffer.UVKind);
  77027. defines.push("#define UV1");
  77028. }
  77029. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77030. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77031. defines.push("#define UV2");
  77032. }
  77033. }
  77034. // Buffers
  77035. if (this._enablePosition) {
  77036. defines.push("#define POSITION");
  77037. }
  77038. // Bones
  77039. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77040. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77041. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77042. if (mesh.numBoneInfluencers > 4) {
  77043. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77044. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77045. }
  77046. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77047. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  77048. }
  77049. else {
  77050. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77051. }
  77052. // Instances
  77053. if (useInstances) {
  77054. defines.push("#define INSTANCES");
  77055. attribs.push("world0");
  77056. attribs.push("world1");
  77057. attribs.push("world2");
  77058. attribs.push("world3");
  77059. }
  77060. // Get correct effect
  77061. var join = defines.join("\n");
  77062. if (this._cachedDefines !== join) {
  77063. this._cachedDefines = join;
  77064. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  77065. }
  77066. return this._effect.isReady();
  77067. };
  77068. /**
  77069. * Gets the current underlying G Buffer.
  77070. * @returns the buffer
  77071. */
  77072. GeometryBufferRenderer.prototype.getGBuffer = function () {
  77073. return this._multiRenderTarget;
  77074. };
  77075. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  77076. /**
  77077. * Gets the number of samples used to render the buffer (anti aliasing).
  77078. */
  77079. get: function () {
  77080. return this._multiRenderTarget.samples;
  77081. },
  77082. /**
  77083. * Sets the number of samples used to render the buffer (anti aliasing).
  77084. */
  77085. set: function (value) {
  77086. this._multiRenderTarget.samples = value;
  77087. },
  77088. enumerable: true,
  77089. configurable: true
  77090. });
  77091. /**
  77092. * Disposes the renderer and frees up associated resources.
  77093. */
  77094. GeometryBufferRenderer.prototype.dispose = function () {
  77095. this.getGBuffer().dispose();
  77096. };
  77097. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  77098. var _this = this;
  77099. var engine = this._scene.getEngine();
  77100. var count = this._enablePosition ? 3 : 2;
  77101. 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 });
  77102. if (!this.isSupported) {
  77103. return;
  77104. }
  77105. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77106. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77107. this._multiRenderTarget.refreshRate = 1;
  77108. this._multiRenderTarget.renderParticles = false;
  77109. this._multiRenderTarget.renderList = null;
  77110. // set default depth value to 1.0 (far away)
  77111. this._multiRenderTarget.onClearObservable.add(function (engine) {
  77112. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  77113. });
  77114. // Custom render function
  77115. var renderSubMesh = function (subMesh) {
  77116. var mesh = subMesh.getRenderingMesh();
  77117. var scene = _this._scene;
  77118. var engine = scene.getEngine();
  77119. var material = subMesh.getMaterial();
  77120. if (!material) {
  77121. return;
  77122. }
  77123. // Culling
  77124. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77125. // Managing instances
  77126. var batch = mesh._getInstancesRenderList(subMesh._id);
  77127. if (batch.mustReturn) {
  77128. return;
  77129. }
  77130. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77131. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  77132. engine.enableEffect(_this._effect);
  77133. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77134. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77135. _this._effect.setMatrix("view", scene.getViewMatrix());
  77136. // Alpha test
  77137. if (material && material.needAlphaTesting()) {
  77138. var alphaTexture = material.getAlphaTestTexture();
  77139. if (alphaTexture) {
  77140. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77141. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77142. }
  77143. }
  77144. // Bones
  77145. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77146. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77147. }
  77148. // Draw
  77149. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77150. }
  77151. };
  77152. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77153. var index;
  77154. if (depthOnlySubMeshes.length) {
  77155. engine.setColorWrite(false);
  77156. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77157. renderSubMesh(depthOnlySubMeshes.data[index]);
  77158. }
  77159. engine.setColorWrite(true);
  77160. }
  77161. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77162. renderSubMesh(opaqueSubMeshes.data[index]);
  77163. }
  77164. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77165. renderSubMesh(alphaTestSubMeshes.data[index]);
  77166. }
  77167. };
  77168. };
  77169. return GeometryBufferRenderer;
  77170. }());
  77171. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  77172. })(BABYLON || (BABYLON = {}));
  77173. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  77174. var BABYLON;
  77175. (function (BABYLON) {
  77176. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  77177. get: function () {
  77178. this._geometryBufferRenderer;
  77179. },
  77180. set: function (value) {
  77181. if (value && value.isSupported) {
  77182. this._geometryBufferRenderer = value;
  77183. }
  77184. ;
  77185. },
  77186. enumerable: true,
  77187. configurable: true
  77188. });
  77189. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  77190. if (ratio === void 0) { ratio = 1; }
  77191. if (this._geometryBufferRenderer) {
  77192. return this._geometryBufferRenderer;
  77193. }
  77194. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  77195. if (!this._geometryBufferRenderer.isSupported) {
  77196. this._geometryBufferRenderer = null;
  77197. }
  77198. return this._geometryBufferRenderer;
  77199. };
  77200. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  77201. if (!this._geometryBufferRenderer) {
  77202. return;
  77203. }
  77204. this._geometryBufferRenderer.dispose();
  77205. this._geometryBufferRenderer = null;
  77206. };
  77207. /**
  77208. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer usefull
  77209. * in several rendering techniques.
  77210. */
  77211. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  77212. /**
  77213. * Creates a new instance of the component for the given scene
  77214. * @param scene Defines the scene to register the component in
  77215. */
  77216. function GeometryBufferRendererSceneComponent(scene) {
  77217. /**
  77218. * The component name helpfull to identify the component in the list of scene components.
  77219. */
  77220. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  77221. this.scene = scene;
  77222. }
  77223. /**
  77224. * Registers the component in a given scene
  77225. */
  77226. GeometryBufferRendererSceneComponent.prototype.register = function () {
  77227. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  77228. };
  77229. /**
  77230. * Rebuilds the elements related to this component in case of
  77231. * context lost for instance.
  77232. */
  77233. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  77234. // Nothing to do for this component
  77235. };
  77236. /**
  77237. * Disposes the component and the associated ressources
  77238. */
  77239. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  77240. // Nothing to do for this component
  77241. };
  77242. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77243. if (this.scene._geometryBufferRenderer) {
  77244. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  77245. }
  77246. };
  77247. return GeometryBufferRendererSceneComponent;
  77248. }());
  77249. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  77250. })(BABYLON || (BABYLON = {}));
  77251. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  77252. var BABYLON;
  77253. (function (BABYLON) {
  77254. var SSAORenderingPipeline = /** @class */ (function (_super) {
  77255. __extends(SSAORenderingPipeline, _super);
  77256. /**
  77257. * @constructor
  77258. * @param {string} name - The rendering pipeline name
  77259. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  77260. * @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 }
  77261. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  77262. */
  77263. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  77264. var _this = _super.call(this, scene.getEngine(), name) || this;
  77265. // Members
  77266. /**
  77267. * The PassPostProcess id in the pipeline that contains the original scene color
  77268. */
  77269. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  77270. /**
  77271. * The SSAO PostProcess id in the pipeline
  77272. */
  77273. _this.SSAORenderEffect = "SSAORenderEffect";
  77274. /**
  77275. * The horizontal blur PostProcess id in the pipeline
  77276. */
  77277. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  77278. /**
  77279. * The vertical blur PostProcess id in the pipeline
  77280. */
  77281. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  77282. /**
  77283. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  77284. */
  77285. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  77286. /**
  77287. * The output strength of the SSAO post-process. Default value is 1.0.
  77288. */
  77289. _this.totalStrength = 1.0;
  77290. /**
  77291. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  77292. */
  77293. _this.radius = 0.0001;
  77294. /**
  77295. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  77296. * Must not be equal to fallOff and superior to fallOff.
  77297. * Default value is 0.975
  77298. */
  77299. _this.area = 0.0075;
  77300. /**
  77301. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  77302. * Must not be equal to area and inferior to area.
  77303. * Default value is 0.0
  77304. */
  77305. _this.fallOff = 0.000001;
  77306. /**
  77307. * The base color of the SSAO post-process
  77308. * The final result is "base + ssao" between [0, 1]
  77309. */
  77310. _this.base = 0.5;
  77311. _this._firstUpdate = true;
  77312. _this._scene = scene;
  77313. // Set up assets
  77314. _this._createRandomTexture();
  77315. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  77316. var ssaoRatio = ratio.ssaoRatio || ratio;
  77317. var combineRatio = ratio.combineRatio || ratio;
  77318. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  77319. _this._createSSAOPostProcess(ssaoRatio);
  77320. _this._createBlurPostProcess(ssaoRatio);
  77321. _this._createSSAOCombinePostProcess(combineRatio);
  77322. // Set up pipeline
  77323. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  77324. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  77325. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  77326. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  77327. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  77328. // Finish
  77329. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77330. if (cameras)
  77331. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  77332. return _this;
  77333. }
  77334. // Public Methods
  77335. /**
  77336. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  77337. */
  77338. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  77339. if (disableDepthRender === void 0) { disableDepthRender = false; }
  77340. for (var i = 0; i < this._scene.cameras.length; i++) {
  77341. var camera = this._scene.cameras[i];
  77342. this._originalColorPostProcess.dispose(camera);
  77343. this._ssaoPostProcess.dispose(camera);
  77344. this._blurHPostProcess.dispose(camera);
  77345. this._blurVPostProcess.dispose(camera);
  77346. this._ssaoCombinePostProcess.dispose(camera);
  77347. }
  77348. this._randomTexture.dispose();
  77349. if (disableDepthRender)
  77350. this._scene.disableDepthRenderer();
  77351. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  77352. _super.prototype.dispose.call(this);
  77353. };
  77354. // Private Methods
  77355. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  77356. var _this = this;
  77357. var size = 16;
  77358. 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);
  77359. 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);
  77360. this._blurHPostProcess.onActivateObservable.add(function () {
  77361. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  77362. _this._blurHPostProcess.kernel = size * dw;
  77363. });
  77364. this._blurVPostProcess.onActivateObservable.add(function () {
  77365. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  77366. _this._blurVPostProcess.kernel = size * dw;
  77367. });
  77368. };
  77369. /** @hidden */
  77370. SSAORenderingPipeline.prototype._rebuild = function () {
  77371. this._firstUpdate = true;
  77372. _super.prototype._rebuild.call(this);
  77373. };
  77374. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  77375. var _this = this;
  77376. var numSamples = 16;
  77377. var sampleSphere = [
  77378. 0.5381, 0.1856, -0.4319,
  77379. 0.1379, 0.2486, 0.4430,
  77380. 0.3371, 0.5679, -0.0057,
  77381. -0.6999, -0.0451, -0.0019,
  77382. 0.0689, -0.1598, -0.8547,
  77383. 0.0560, 0.0069, -0.1843,
  77384. -0.0146, 0.1402, 0.0762,
  77385. 0.0100, -0.1924, -0.0344,
  77386. -0.3577, -0.5301, -0.4358,
  77387. -0.3169, 0.1063, 0.0158,
  77388. 0.0103, -0.5869, 0.0046,
  77389. -0.0897, -0.4940, 0.3287,
  77390. 0.7119, -0.0154, -0.0918,
  77391. -0.0533, 0.0596, -0.5411,
  77392. 0.0352, -0.0631, 0.5460,
  77393. -0.4776, 0.2847, -0.0271
  77394. ];
  77395. var samplesFactor = 1.0 / numSamples;
  77396. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  77397. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  77398. "area", "fallOff", "base", "range", "viewport"
  77399. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  77400. this._ssaoPostProcess.onApply = function (effect) {
  77401. if (_this._firstUpdate) {
  77402. effect.setArray3("sampleSphere", sampleSphere);
  77403. effect.setFloat("samplesFactor", samplesFactor);
  77404. effect.setFloat("randTextureTiles", 4.0);
  77405. }
  77406. effect.setFloat("totalStrength", _this.totalStrength);
  77407. effect.setFloat("radius", _this.radius);
  77408. effect.setFloat("area", _this.area);
  77409. effect.setFloat("fallOff", _this.fallOff);
  77410. effect.setFloat("base", _this.base);
  77411. effect.setTexture("textureSampler", _this._depthTexture);
  77412. effect.setTexture("randomSampler", _this._randomTexture);
  77413. };
  77414. };
  77415. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  77416. var _this = this;
  77417. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  77418. this._ssaoCombinePostProcess.onApply = function (effect) {
  77419. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  77420. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  77421. };
  77422. };
  77423. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  77424. var size = 512;
  77425. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77426. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  77427. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  77428. var context = this._randomTexture.getContext();
  77429. var rand = function (min, max) {
  77430. return Math.random() * (max - min) + min;
  77431. };
  77432. var randVector = BABYLON.Vector3.Zero();
  77433. for (var x = 0; x < size; x++) {
  77434. for (var y = 0; y < size; y++) {
  77435. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  77436. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  77437. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  77438. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  77439. context.fillRect(x, y, 1, 1);
  77440. }
  77441. }
  77442. this._randomTexture.update(false);
  77443. };
  77444. __decorate([
  77445. BABYLON.serialize()
  77446. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  77447. __decorate([
  77448. BABYLON.serialize()
  77449. ], SSAORenderingPipeline.prototype, "radius", void 0);
  77450. __decorate([
  77451. BABYLON.serialize()
  77452. ], SSAORenderingPipeline.prototype, "area", void 0);
  77453. __decorate([
  77454. BABYLON.serialize()
  77455. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  77456. __decorate([
  77457. BABYLON.serialize()
  77458. ], SSAORenderingPipeline.prototype, "base", void 0);
  77459. return SSAORenderingPipeline;
  77460. }(BABYLON.PostProcessRenderPipeline));
  77461. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  77462. })(BABYLON || (BABYLON = {}));
  77463. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  77464. var BABYLON;
  77465. (function (BABYLON) {
  77466. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  77467. __extends(SSAO2RenderingPipeline, _super);
  77468. /**
  77469. * @constructor
  77470. * @param {string} name - The rendering pipeline name
  77471. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  77472. * @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 }
  77473. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  77474. */
  77475. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  77476. var _this = _super.call(this, scene.getEngine(), name) || this;
  77477. // Members
  77478. /**
  77479. * The PassPostProcess id in the pipeline that contains the original scene color
  77480. */
  77481. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  77482. /**
  77483. * The SSAO PostProcess id in the pipeline
  77484. */
  77485. _this.SSAORenderEffect = "SSAORenderEffect";
  77486. /**
  77487. * The horizontal blur PostProcess id in the pipeline
  77488. */
  77489. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  77490. /**
  77491. * The vertical blur PostProcess id in the pipeline
  77492. */
  77493. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  77494. /**
  77495. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  77496. */
  77497. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  77498. /**
  77499. * The output strength of the SSAO post-process. Default value is 1.0.
  77500. */
  77501. _this.totalStrength = 1.0;
  77502. /**
  77503. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  77504. */
  77505. _this.maxZ = 100.0;
  77506. /**
  77507. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  77508. */
  77509. _this.minZAspect = 0.2;
  77510. _this._samples = 8;
  77511. _this._textureSamples = 1;
  77512. /**
  77513. * Are we using bilateral blur ?
  77514. */
  77515. _this._expensiveBlur = true;
  77516. /**
  77517. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  77518. */
  77519. _this.radius = 2.0;
  77520. /**
  77521. * The base color of the SSAO post-process
  77522. * The final result is "base + ssao" between [0, 1]
  77523. */
  77524. _this.base = 0;
  77525. _this._firstUpdate = true;
  77526. _this._bits = new Uint32Array(1);
  77527. _this._scene = scene;
  77528. _this._ratio = ratio;
  77529. if (!_this.isSupported) {
  77530. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  77531. return _this;
  77532. }
  77533. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  77534. var blurRatio = _this._ratio.blurRatio || ratio;
  77535. // Set up assets
  77536. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  77537. _this._createRandomTexture();
  77538. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  77539. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  77540. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  77541. _this._originalColorPostProcess.samples = _this.textureSamples;
  77542. _this._createSSAOPostProcess(1.0);
  77543. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  77544. _this._createSSAOCombinePostProcess(blurRatio);
  77545. // Set up pipeline
  77546. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  77547. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  77548. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  77549. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  77550. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  77551. // Finish
  77552. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77553. if (cameras)
  77554. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  77555. return _this;
  77556. }
  77557. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  77558. get: function () {
  77559. return this._samples;
  77560. },
  77561. /**
  77562. * Number of samples used for the SSAO calculations. Default value is 8
  77563. */
  77564. set: function (n) {
  77565. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  77566. this._samples = n;
  77567. this._sampleSphere = this._generateHemisphere();
  77568. this._firstUpdate = true;
  77569. },
  77570. enumerable: true,
  77571. configurable: true
  77572. });
  77573. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  77574. get: function () {
  77575. return this._textureSamples;
  77576. },
  77577. /**
  77578. * Number of samples to use for antialiasing
  77579. */
  77580. set: function (n) {
  77581. this._textureSamples = n;
  77582. this._originalColorPostProcess.samples = n;
  77583. this._blurHPostProcess.samples = n;
  77584. this._blurVPostProcess.samples = n;
  77585. this._ssaoPostProcess.samples = n;
  77586. this._ssaoCombinePostProcess.samples = n;
  77587. },
  77588. enumerable: true,
  77589. configurable: true
  77590. });
  77591. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  77592. get: function () {
  77593. return this._expensiveBlur;
  77594. },
  77595. set: function (b) {
  77596. 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"]);
  77597. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  77598. this._expensiveBlur = b;
  77599. this._firstUpdate = true;
  77600. },
  77601. enumerable: true,
  77602. configurable: true
  77603. });
  77604. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  77605. /**
  77606. * Support test.
  77607. */
  77608. get: function () {
  77609. var engine = BABYLON.Engine.LastCreatedEngine;
  77610. if (!engine) {
  77611. return false;
  77612. }
  77613. return engine.getCaps().drawBuffersExtension;
  77614. },
  77615. enumerable: true,
  77616. configurable: true
  77617. });
  77618. // Public Methods
  77619. /**
  77620. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  77621. */
  77622. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  77623. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  77624. for (var i = 0; i < this._scene.cameras.length; i++) {
  77625. var camera = this._scene.cameras[i];
  77626. this._originalColorPostProcess.dispose(camera);
  77627. this._ssaoPostProcess.dispose(camera);
  77628. this._blurHPostProcess.dispose(camera);
  77629. this._blurVPostProcess.dispose(camera);
  77630. this._ssaoCombinePostProcess.dispose(camera);
  77631. }
  77632. this._randomTexture.dispose();
  77633. if (disableGeometryBufferRenderer)
  77634. this._scene.disableGeometryBufferRenderer();
  77635. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  77636. _super.prototype.dispose.call(this);
  77637. };
  77638. // Private Methods
  77639. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  77640. var _this = this;
  77641. this._samplerOffsets = [];
  77642. var expensive = this.expensiveBlur;
  77643. for (var i = -8; i < 8; i++) {
  77644. this._samplerOffsets.push(i * 2 + 0.5);
  77645. }
  77646. 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");
  77647. this._blurHPostProcess.onApply = function (effect) {
  77648. if (!_this._scene.activeCamera) {
  77649. return;
  77650. }
  77651. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  77652. effect.setFloat("near", _this._scene.activeCamera.minZ);
  77653. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  77654. effect.setFloat("radius", _this.radius);
  77655. effect.setTexture("depthSampler", _this._depthTexture);
  77656. if (_this._firstUpdate) {
  77657. effect.setArray("samplerOffsets", _this._samplerOffsets);
  77658. }
  77659. };
  77660. 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");
  77661. this._blurVPostProcess.onApply = function (effect) {
  77662. if (!_this._scene.activeCamera) {
  77663. return;
  77664. }
  77665. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  77666. effect.setFloat("near", _this._scene.activeCamera.minZ);
  77667. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  77668. effect.setFloat("radius", _this.radius);
  77669. effect.setTexture("depthSampler", _this._depthTexture);
  77670. if (_this._firstUpdate) {
  77671. effect.setArray("samplerOffsets", _this._samplerOffsets);
  77672. _this._firstUpdate = false;
  77673. }
  77674. };
  77675. this._blurHPostProcess.samples = this.textureSamples;
  77676. this._blurVPostProcess.samples = this.textureSamples;
  77677. };
  77678. /** @hidden */
  77679. SSAO2RenderingPipeline.prototype._rebuild = function () {
  77680. this._firstUpdate = true;
  77681. _super.prototype._rebuild.call(this);
  77682. };
  77683. //Van der Corput radical inverse
  77684. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  77685. this._bits[0] = i;
  77686. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  77687. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  77688. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  77689. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  77690. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  77691. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  77692. };
  77693. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  77694. return [i / n, this._radicalInverse_VdC(i)];
  77695. };
  77696. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  77697. var phi = v * 2.0 * Math.PI;
  77698. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  77699. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  77700. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  77701. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  77702. };
  77703. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  77704. var numSamples = this.samples;
  77705. var result = [];
  77706. var vector;
  77707. var i = 0;
  77708. while (i < numSamples) {
  77709. if (numSamples < 16) {
  77710. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  77711. }
  77712. else {
  77713. var rand = this._hammersley(i, numSamples);
  77714. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  77715. }
  77716. result.push(vector.x, vector.y, vector.z);
  77717. i++;
  77718. }
  77719. return result;
  77720. };
  77721. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  77722. var _this = this;
  77723. var numSamples = this.samples;
  77724. this._sampleSphere = this._generateHemisphere();
  77725. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  77726. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  77727. "base", "range", "projection", "near", "far", "texelSize",
  77728. "xViewport", "yViewport", "maxZ", "minZAspect"
  77729. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  77730. this._ssaoPostProcess.onApply = function (effect) {
  77731. if (_this._firstUpdate) {
  77732. effect.setArray3("sampleSphere", _this._sampleSphere);
  77733. effect.setFloat("randTextureTiles", 32.0);
  77734. }
  77735. if (!_this._scene.activeCamera) {
  77736. return;
  77737. }
  77738. effect.setFloat("samplesFactor", 1 / _this.samples);
  77739. effect.setFloat("totalStrength", _this.totalStrength);
  77740. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  77741. effect.setFloat("radius", _this.radius);
  77742. effect.setFloat("maxZ", _this.maxZ);
  77743. effect.setFloat("minZAspect", _this.minZAspect);
  77744. effect.setFloat("base", _this.base);
  77745. effect.setFloat("near", _this._scene.activeCamera.minZ);
  77746. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  77747. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  77748. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  77749. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  77750. effect.setTexture("textureSampler", _this._depthTexture);
  77751. effect.setTexture("normalSampler", _this._normalTexture);
  77752. effect.setTexture("randomSampler", _this._randomTexture);
  77753. };
  77754. this._ssaoPostProcess.samples = this.textureSamples;
  77755. };
  77756. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  77757. var _this = this;
  77758. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  77759. this._ssaoCombinePostProcess.onApply = function (effect) {
  77760. var viewport = _this._scene.activeCamera.viewport;
  77761. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  77762. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  77763. };
  77764. this._ssaoCombinePostProcess.samples = this.textureSamples;
  77765. };
  77766. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  77767. var size = 128;
  77768. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77769. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  77770. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  77771. var context = this._randomTexture.getContext();
  77772. var rand = function (min, max) {
  77773. return Math.random() * (max - min) + min;
  77774. };
  77775. var randVector = BABYLON.Vector3.Zero();
  77776. for (var x = 0; x < size; x++) {
  77777. for (var y = 0; y < size; y++) {
  77778. randVector.x = rand(0.0, 1.0);
  77779. randVector.y = rand(0.0, 1.0);
  77780. randVector.z = 0.0;
  77781. randVector.normalize();
  77782. randVector.scaleInPlace(255);
  77783. randVector.x = Math.floor(randVector.x);
  77784. randVector.y = Math.floor(randVector.y);
  77785. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  77786. context.fillRect(x, y, 1, 1);
  77787. }
  77788. }
  77789. this._randomTexture.update(false);
  77790. };
  77791. /**
  77792. * Serialize the rendering pipeline (Used when exporting)
  77793. * @returns the serialized object
  77794. */
  77795. SSAO2RenderingPipeline.prototype.serialize = function () {
  77796. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  77797. serializationObject.customType = "SSAO2RenderingPipeline";
  77798. return serializationObject;
  77799. };
  77800. /**
  77801. * Parse the serialized pipeline
  77802. * @param source Source pipeline.
  77803. * @param scene The scene to load the pipeline to.
  77804. * @param rootUrl The URL of the serialized pipeline.
  77805. * @returns An instantiated pipeline from the serialized object.
  77806. */
  77807. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  77808. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  77809. };
  77810. __decorate([
  77811. BABYLON.serialize()
  77812. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  77813. __decorate([
  77814. BABYLON.serialize()
  77815. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  77816. __decorate([
  77817. BABYLON.serialize()
  77818. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  77819. __decorate([
  77820. BABYLON.serialize("samples")
  77821. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  77822. __decorate([
  77823. BABYLON.serialize("textureSamples")
  77824. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  77825. __decorate([
  77826. BABYLON.serialize()
  77827. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  77828. __decorate([
  77829. BABYLON.serialize("expensiveBlur")
  77830. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  77831. __decorate([
  77832. BABYLON.serialize()
  77833. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  77834. __decorate([
  77835. BABYLON.serialize()
  77836. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  77837. return SSAO2RenderingPipeline;
  77838. }(BABYLON.PostProcessRenderPipeline));
  77839. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  77840. })(BABYLON || (BABYLON = {}));
  77841. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  77842. // BABYLON.JS Chromatic Aberration GLSL Shader
  77843. // Author: Olivier Guyot
  77844. // Separates very slightly R, G and B colors on the edges of the screen
  77845. // Inspired by Francois Tarlier & Martins Upitis
  77846. var BABYLON;
  77847. (function (BABYLON) {
  77848. var LensRenderingPipeline = /** @class */ (function (_super) {
  77849. __extends(LensRenderingPipeline, _super);
  77850. /**
  77851. * @constructor
  77852. *
  77853. * Effect parameters are as follow:
  77854. * {
  77855. * chromatic_aberration: number; // from 0 to x (1 for realism)
  77856. * edge_blur: number; // from 0 to x (1 for realism)
  77857. * distortion: number; // from 0 to x (1 for realism)
  77858. * grain_amount: number; // from 0 to 1
  77859. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  77860. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  77861. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  77862. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  77863. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  77864. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  77865. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  77866. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  77867. * }
  77868. * Note: if an effect parameter is unset, effect is disabled
  77869. *
  77870. * @param {string} name - The rendering pipeline name
  77871. * @param {object} parameters - An object containing all parameters (see above)
  77872. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  77873. * @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)
  77874. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  77875. */
  77876. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  77877. if (ratio === void 0) { ratio = 1.0; }
  77878. var _this = _super.call(this, scene.getEngine(), name) || this;
  77879. // Lens effects can be of the following:
  77880. // - chromatic aberration (slight shift of RGB colors)
  77881. // - blur on the edge of the lens
  77882. // - lens distortion
  77883. // - depth-of-field blur & highlights enhancing
  77884. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  77885. // - grain effect (noise or custom texture)
  77886. // Two additional texture samplers are needed:
  77887. // - depth map (for depth-of-field)
  77888. // - grain texture
  77889. /**
  77890. * The chromatic aberration PostProcess id in the pipeline
  77891. */
  77892. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  77893. /**
  77894. * The highlights enhancing PostProcess id in the pipeline
  77895. */
  77896. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  77897. /**
  77898. * The depth-of-field PostProcess id in the pipeline
  77899. */
  77900. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  77901. _this._scene = scene;
  77902. // Fetch texture samplers
  77903. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  77904. if (parameters.grain_texture) {
  77905. _this._grainTexture = parameters.grain_texture;
  77906. }
  77907. else {
  77908. _this._createGrainTexture();
  77909. }
  77910. // save parameters
  77911. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  77912. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  77913. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  77914. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  77915. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  77916. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  77917. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  77918. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  77919. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  77920. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  77921. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  77922. // Create effects
  77923. _this._createChromaticAberrationPostProcess(ratio);
  77924. _this._createHighlightsPostProcess(ratio);
  77925. _this._createDepthOfFieldPostProcess(ratio / 4);
  77926. // Set up pipeline
  77927. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  77928. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  77929. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  77930. if (_this._highlightsGain === -1) {
  77931. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  77932. }
  77933. // Finish
  77934. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77935. if (cameras) {
  77936. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  77937. }
  77938. return _this;
  77939. }
  77940. // public methods (self explanatory)
  77941. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  77942. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  77943. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  77944. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  77945. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  77946. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  77947. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  77948. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  77949. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  77950. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  77951. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  77952. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  77953. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  77954. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  77955. };
  77956. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  77957. this._highlightsPostProcess.updateEffect();
  77958. };
  77959. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  77960. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  77961. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  77962. this._highlightsGain = amount;
  77963. };
  77964. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  77965. if (this._highlightsGain === -1) {
  77966. this._highlightsGain = 1.0;
  77967. }
  77968. this._highlightsThreshold = amount;
  77969. };
  77970. LensRenderingPipeline.prototype.disableHighlights = function () {
  77971. this._highlightsGain = -1;
  77972. };
  77973. /**
  77974. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  77975. */
  77976. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  77977. if (disableDepthRender === void 0) { disableDepthRender = false; }
  77978. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  77979. this._chromaticAberrationPostProcess = null;
  77980. this._highlightsPostProcess = null;
  77981. this._depthOfFieldPostProcess = null;
  77982. this._grainTexture.dispose();
  77983. if (disableDepthRender)
  77984. this._scene.disableDepthRenderer();
  77985. };
  77986. // colors shifting and distortion
  77987. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  77988. var _this = this;
  77989. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  77990. [], // samplers
  77991. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  77992. this._chromaticAberrationPostProcess.onApply = function (effect) {
  77993. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  77994. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  77995. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  77996. effect.setFloat('radialIntensity', 1);
  77997. effect.setFloat2('direction', 17, 17);
  77998. effect.setFloat2('centerPosition', 0.5, 0.5);
  77999. };
  78000. };
  78001. // highlights enhancing
  78002. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  78003. var _this = this;
  78004. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  78005. [], // samplers
  78006. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  78007. this._highlightsPostProcess.onApply = function (effect) {
  78008. effect.setFloat('gain', _this._highlightsGain);
  78009. effect.setFloat('threshold', _this._highlightsThreshold);
  78010. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  78011. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  78012. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  78013. };
  78014. };
  78015. // colors shifting and distortion
  78016. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  78017. var _this = this;
  78018. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  78019. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  78020. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  78021. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78022. this._depthOfFieldPostProcess.onApply = function (effect) {
  78023. effect.setTexture("depthSampler", _this._depthTexture);
  78024. effect.setTexture("grainSampler", _this._grainTexture);
  78025. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  78026. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  78027. effect.setFloat('grain_amount', _this._grainAmount);
  78028. effect.setBool('blur_noise', _this._blurNoise);
  78029. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  78030. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  78031. effect.setFloat('distortion', _this._distortion);
  78032. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  78033. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  78034. effect.setFloat('aperture', _this._dofAperture);
  78035. effect.setFloat('darken', _this._dofDarken);
  78036. effect.setFloat('edge_blur', _this._edgeBlur);
  78037. effect.setBool('highlights', (_this._highlightsGain !== -1));
  78038. if (_this._scene.activeCamera) {
  78039. effect.setFloat('near', _this._scene.activeCamera.minZ);
  78040. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  78041. }
  78042. };
  78043. };
  78044. // creates a black and white random noise texture, 512x512
  78045. LensRenderingPipeline.prototype._createGrainTexture = function () {
  78046. var size = 512;
  78047. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78048. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  78049. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  78050. var context = this._grainTexture.getContext();
  78051. var rand = function (min, max) {
  78052. return Math.random() * (max - min) + min;
  78053. };
  78054. var value;
  78055. for (var x = 0; x < size; x++) {
  78056. for (var y = 0; y < size; y++) {
  78057. value = Math.floor(rand(0.42, 0.58) * 255);
  78058. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  78059. context.fillRect(x, y, 1, 1);
  78060. }
  78061. }
  78062. this._grainTexture.update(false);
  78063. };
  78064. return LensRenderingPipeline;
  78065. }(BABYLON.PostProcessRenderPipeline));
  78066. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  78067. })(BABYLON || (BABYLON = {}));
  78068. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  78069. var BABYLON;
  78070. (function (BABYLON) {
  78071. var StandardRenderingPipeline = /** @class */ (function (_super) {
  78072. __extends(StandardRenderingPipeline, _super);
  78073. /**
  78074. * @constructor
  78075. * @param {string} name - The rendering pipeline name
  78076. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78077. * @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)
  78078. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  78079. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78080. */
  78081. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  78082. if (originalPostProcess === void 0) { originalPostProcess = null; }
  78083. var _this = _super.call(this, scene.getEngine(), name) || this;
  78084. _this.downSampleX4PostProcess = null;
  78085. _this.brightPassPostProcess = null;
  78086. _this.blurHPostProcesses = [];
  78087. _this.blurVPostProcesses = [];
  78088. _this.textureAdderPostProcess = null;
  78089. _this.volumetricLightPostProcess = null;
  78090. _this.volumetricLightSmoothXPostProcess = null;
  78091. _this.volumetricLightSmoothYPostProcess = null;
  78092. _this.volumetricLightMergePostProces = null;
  78093. _this.volumetricLightFinalPostProcess = null;
  78094. _this.luminancePostProcess = null;
  78095. _this.luminanceDownSamplePostProcesses = [];
  78096. _this.hdrPostProcess = null;
  78097. _this.textureAdderFinalPostProcess = null;
  78098. _this.lensFlareFinalPostProcess = null;
  78099. _this.hdrFinalPostProcess = null;
  78100. _this.lensFlarePostProcess = null;
  78101. _this.lensFlareComposePostProcess = null;
  78102. _this.motionBlurPostProcess = null;
  78103. _this.depthOfFieldPostProcess = null;
  78104. // Values
  78105. _this.brightThreshold = 1.0;
  78106. _this.blurWidth = 512.0;
  78107. _this.horizontalBlur = false;
  78108. _this.exposure = 1.0;
  78109. _this.lensTexture = null;
  78110. _this.volumetricLightCoefficient = 0.2;
  78111. _this.volumetricLightPower = 4.0;
  78112. _this.volumetricLightBlurScale = 64.0;
  78113. _this.sourceLight = null;
  78114. _this.hdrMinimumLuminance = 1.0;
  78115. _this.hdrDecreaseRate = 0.5;
  78116. _this.hdrIncreaseRate = 0.5;
  78117. _this.lensColorTexture = null;
  78118. _this.lensFlareStrength = 20.0;
  78119. _this.lensFlareGhostDispersal = 1.4;
  78120. _this.lensFlareHaloWidth = 0.7;
  78121. _this.lensFlareDistortionStrength = 16.0;
  78122. _this.lensStarTexture = null;
  78123. _this.lensFlareDirtTexture = null;
  78124. _this.depthOfFieldDistance = 10.0;
  78125. _this.depthOfFieldBlurWidth = 64.0;
  78126. _this.motionStrength = 1.0;
  78127. // IAnimatable
  78128. _this.animations = [];
  78129. _this._currentDepthOfFieldSource = null;
  78130. _this._hdrCurrentLuminance = 1.0;
  78131. // Getters and setters
  78132. _this._bloomEnabled = true;
  78133. _this._depthOfFieldEnabled = false;
  78134. _this._vlsEnabled = false;
  78135. _this._lensFlareEnabled = false;
  78136. _this._hdrEnabled = false;
  78137. _this._motionBlurEnabled = false;
  78138. _this._motionBlurSamples = 64.0;
  78139. _this._volumetricLightStepsCount = 50.0;
  78140. _this._cameras = cameras || [];
  78141. // Initialize
  78142. _this._scene = scene;
  78143. _this._basePostProcess = originalPostProcess;
  78144. _this._ratio = ratio;
  78145. // Misc
  78146. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78147. // Finish
  78148. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78149. _this._buildPipeline();
  78150. return _this;
  78151. }
  78152. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  78153. get: function () {
  78154. return this._bloomEnabled;
  78155. },
  78156. set: function (enabled) {
  78157. if (this._bloomEnabled === enabled) {
  78158. return;
  78159. }
  78160. this._bloomEnabled = enabled;
  78161. this._buildPipeline();
  78162. },
  78163. enumerable: true,
  78164. configurable: true
  78165. });
  78166. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  78167. get: function () {
  78168. return this._depthOfFieldEnabled;
  78169. },
  78170. set: function (enabled) {
  78171. if (this._depthOfFieldEnabled === enabled) {
  78172. return;
  78173. }
  78174. this._depthOfFieldEnabled = enabled;
  78175. this._buildPipeline();
  78176. },
  78177. enumerable: true,
  78178. configurable: true
  78179. });
  78180. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  78181. get: function () {
  78182. return this._lensFlareEnabled;
  78183. },
  78184. set: function (enabled) {
  78185. if (this._lensFlareEnabled === enabled) {
  78186. return;
  78187. }
  78188. this._lensFlareEnabled = enabled;
  78189. this._buildPipeline();
  78190. },
  78191. enumerable: true,
  78192. configurable: true
  78193. });
  78194. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  78195. get: function () {
  78196. return this._hdrEnabled;
  78197. },
  78198. set: function (enabled) {
  78199. if (this._hdrEnabled === enabled) {
  78200. return;
  78201. }
  78202. this._hdrEnabled = enabled;
  78203. this._buildPipeline();
  78204. },
  78205. enumerable: true,
  78206. configurable: true
  78207. });
  78208. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  78209. get: function () {
  78210. return this._vlsEnabled;
  78211. },
  78212. set: function (enabled) {
  78213. if (this._vlsEnabled === enabled) {
  78214. return;
  78215. }
  78216. if (enabled) {
  78217. var geometry = this._scene.enableGeometryBufferRenderer();
  78218. if (!geometry) {
  78219. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  78220. return;
  78221. }
  78222. }
  78223. this._vlsEnabled = enabled;
  78224. this._buildPipeline();
  78225. },
  78226. enumerable: true,
  78227. configurable: true
  78228. });
  78229. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  78230. get: function () {
  78231. return this._motionBlurEnabled;
  78232. },
  78233. set: function (enabled) {
  78234. if (this._motionBlurEnabled === enabled) {
  78235. return;
  78236. }
  78237. this._motionBlurEnabled = enabled;
  78238. this._buildPipeline();
  78239. },
  78240. enumerable: true,
  78241. configurable: true
  78242. });
  78243. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  78244. get: function () {
  78245. return this._volumetricLightStepsCount;
  78246. },
  78247. set: function (count) {
  78248. if (this.volumetricLightPostProcess) {
  78249. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  78250. }
  78251. this._volumetricLightStepsCount = count;
  78252. },
  78253. enumerable: true,
  78254. configurable: true
  78255. });
  78256. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  78257. get: function () {
  78258. return this._motionBlurSamples;
  78259. },
  78260. set: function (samples) {
  78261. if (this.motionBlurPostProcess) {
  78262. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  78263. }
  78264. this._motionBlurSamples = samples;
  78265. },
  78266. enumerable: true,
  78267. configurable: true
  78268. });
  78269. StandardRenderingPipeline.prototype._buildPipeline = function () {
  78270. var _this = this;
  78271. var ratio = this._ratio;
  78272. var scene = this._scene;
  78273. this._disposePostProcesses();
  78274. this._reset();
  78275. // Create pass post-process
  78276. if (!this._basePostProcess) {
  78277. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  78278. this.originalPostProcess.onApply = function (effect) {
  78279. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  78280. };
  78281. }
  78282. else {
  78283. this.originalPostProcess = this._basePostProcess;
  78284. }
  78285. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  78286. this._currentDepthOfFieldSource = this.originalPostProcess;
  78287. if (this._bloomEnabled) {
  78288. // Create down sample X4 post-process
  78289. this._createDownSampleX4PostProcess(scene, ratio / 2);
  78290. // Create bright pass post-process
  78291. this._createBrightPassPostProcess(scene, ratio / 2);
  78292. // Create gaussian blur post-processes (down sampling blurs)
  78293. this._createBlurPostProcesses(scene, ratio / 4, 1);
  78294. // Create texture adder post-process
  78295. this._createTextureAdderPostProcess(scene, ratio);
  78296. // Create depth-of-field source post-process
  78297. 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);
  78298. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  78299. }
  78300. if (this._vlsEnabled) {
  78301. // Create volumetric light
  78302. this._createVolumetricLightPostProcess(scene, ratio);
  78303. // Create volumetric light final post-process
  78304. 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);
  78305. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  78306. }
  78307. if (this._lensFlareEnabled) {
  78308. // Create lens flare post-process
  78309. this._createLensFlarePostProcess(scene, ratio);
  78310. // Create depth-of-field source post-process post lens-flare and disable it now
  78311. 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);
  78312. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  78313. }
  78314. if (this._hdrEnabled) {
  78315. // Create luminance
  78316. this._createLuminancePostProcesses(scene, this._floatTextureType);
  78317. // Create HDR
  78318. this._createHdrPostProcess(scene, ratio);
  78319. // Create depth-of-field source post-process post hdr and disable it now
  78320. 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);
  78321. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  78322. }
  78323. if (this._depthOfFieldEnabled) {
  78324. // Create gaussian blur used by depth-of-field
  78325. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  78326. // Create depth-of-field post-process
  78327. this._createDepthOfFieldPostProcess(scene, ratio);
  78328. }
  78329. if (this._motionBlurEnabled) {
  78330. // Create motion blur post-process
  78331. this._createMotionBlurPostProcess(scene, ratio);
  78332. }
  78333. if (this._cameras !== null) {
  78334. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  78335. }
  78336. };
  78337. // Down Sample X4 Post-Processs
  78338. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  78339. var _this = this;
  78340. var downSampleX4Offsets = new Array(32);
  78341. 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);
  78342. this.downSampleX4PostProcess.onApply = function (effect) {
  78343. var id = 0;
  78344. var width = _this.downSampleX4PostProcess.width;
  78345. var height = _this.downSampleX4PostProcess.height;
  78346. for (var i = -2; i < 2; i++) {
  78347. for (var j = -2; j < 2; j++) {
  78348. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  78349. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  78350. id += 2;
  78351. }
  78352. }
  78353. effect.setArray2("dsOffsets", downSampleX4Offsets);
  78354. };
  78355. // Add to pipeline
  78356. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  78357. };
  78358. // Brightpass Post-Process
  78359. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  78360. var _this = this;
  78361. var brightOffsets = new Array(8);
  78362. 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);
  78363. this.brightPassPostProcess.onApply = function (effect) {
  78364. var sU = (1.0 / _this.brightPassPostProcess.width);
  78365. var sV = (1.0 / _this.brightPassPostProcess.height);
  78366. brightOffsets[0] = -0.5 * sU;
  78367. brightOffsets[1] = 0.5 * sV;
  78368. brightOffsets[2] = 0.5 * sU;
  78369. brightOffsets[3] = 0.5 * sV;
  78370. brightOffsets[4] = -0.5 * sU;
  78371. brightOffsets[5] = -0.5 * sV;
  78372. brightOffsets[6] = 0.5 * sU;
  78373. brightOffsets[7] = -0.5 * sV;
  78374. effect.setArray2("dsOffsets", brightOffsets);
  78375. effect.setFloat("brightThreshold", _this.brightThreshold);
  78376. };
  78377. // Add to pipeline
  78378. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  78379. };
  78380. // Create blur H&V post-processes
  78381. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  78382. var _this = this;
  78383. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  78384. var engine = scene.getEngine();
  78385. 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);
  78386. 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);
  78387. blurX.onActivateObservable.add(function () {
  78388. var dw = blurX.width / engine.getRenderWidth();
  78389. blurX.kernel = _this[blurWidthKey] * dw;
  78390. });
  78391. blurY.onActivateObservable.add(function () {
  78392. var dw = blurY.height / engine.getRenderHeight();
  78393. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  78394. });
  78395. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  78396. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  78397. this.blurHPostProcesses.push(blurX);
  78398. this.blurVPostProcesses.push(blurY);
  78399. };
  78400. // Create texture adder post-process
  78401. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  78402. var _this = this;
  78403. 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);
  78404. this.textureAdderPostProcess.onApply = function (effect) {
  78405. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  78406. effect.setTexture("lensSampler", _this.lensTexture);
  78407. effect.setFloat("exposure", _this.exposure);
  78408. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  78409. };
  78410. // Add to pipeline
  78411. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  78412. };
  78413. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  78414. var _this = this;
  78415. var geometryRenderer = scene.enableGeometryBufferRenderer();
  78416. geometryRenderer.enablePosition = true;
  78417. var geometry = geometryRenderer.getGBuffer();
  78418. // Base post-process
  78419. 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));
  78420. var depthValues = BABYLON.Vector2.Zero();
  78421. this.volumetricLightPostProcess.onApply = function (effect) {
  78422. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  78423. var generator = _this.sourceLight.getShadowGenerator();
  78424. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  78425. effect.setTexture("positionSampler", geometry.textures[2]);
  78426. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  78427. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  78428. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  78429. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  78430. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  78431. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  78432. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  78433. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  78434. effect.setVector2("depthValues", depthValues);
  78435. }
  78436. };
  78437. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  78438. // Smooth
  78439. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  78440. // Merge
  78441. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  78442. this.volumetricLightMergePostProces.onApply = function (effect) {
  78443. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  78444. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  78445. };
  78446. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  78447. };
  78448. // Create luminance
  78449. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  78450. var _this = this;
  78451. // Create luminance
  78452. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  78453. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  78454. var offsets = [];
  78455. this.luminancePostProcess.onApply = function (effect) {
  78456. var sU = (1.0 / _this.luminancePostProcess.width);
  78457. var sV = (1.0 / _this.luminancePostProcess.height);
  78458. offsets[0] = -0.5 * sU;
  78459. offsets[1] = 0.5 * sV;
  78460. offsets[2] = 0.5 * sU;
  78461. offsets[3] = 0.5 * sV;
  78462. offsets[4] = -0.5 * sU;
  78463. offsets[5] = -0.5 * sV;
  78464. offsets[6] = 0.5 * sU;
  78465. offsets[7] = -0.5 * sV;
  78466. effect.setArray2("lumOffsets", offsets);
  78467. };
  78468. // Add to pipeline
  78469. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  78470. // Create down sample luminance
  78471. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  78472. var size = Math.pow(3, i);
  78473. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  78474. if (i === 0) {
  78475. defines += "#define FINAL_DOWN_SAMPLER";
  78476. }
  78477. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  78478. this.luminanceDownSamplePostProcesses.push(postProcess);
  78479. }
  78480. // Create callbacks and add effects
  78481. var lastLuminance = this.luminancePostProcess;
  78482. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  78483. var downSampleOffsets = new Array(18);
  78484. pp.onApply = function (effect) {
  78485. if (!lastLuminance) {
  78486. return;
  78487. }
  78488. var id = 0;
  78489. for (var x = -1; x < 2; x++) {
  78490. for (var y = -1; y < 2; y++) {
  78491. downSampleOffsets[id] = x / lastLuminance.width;
  78492. downSampleOffsets[id + 1] = y / lastLuminance.height;
  78493. id += 2;
  78494. }
  78495. }
  78496. effect.setArray2("dsOffsets", downSampleOffsets);
  78497. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  78498. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  78499. lastLuminance = _this.luminancePostProcess;
  78500. }
  78501. else {
  78502. lastLuminance = pp;
  78503. }
  78504. };
  78505. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  78506. pp.onAfterRender = function (effect) {
  78507. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  78508. 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);
  78509. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  78510. };
  78511. }
  78512. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  78513. });
  78514. };
  78515. // Create HDR post-process
  78516. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  78517. var _this = this;
  78518. 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);
  78519. var outputLiminance = 1;
  78520. var time = 0;
  78521. var lastTime = 0;
  78522. this.hdrPostProcess.onApply = function (effect) {
  78523. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  78524. time += scene.getEngine().getDeltaTime();
  78525. if (outputLiminance < 0) {
  78526. outputLiminance = _this._hdrCurrentLuminance;
  78527. }
  78528. else {
  78529. var dt = (lastTime - time) / 1000.0;
  78530. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  78531. outputLiminance += _this.hdrDecreaseRate * dt;
  78532. }
  78533. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  78534. outputLiminance -= _this.hdrIncreaseRate * dt;
  78535. }
  78536. else {
  78537. outputLiminance = _this._hdrCurrentLuminance;
  78538. }
  78539. }
  78540. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  78541. effect.setFloat("averageLuminance", outputLiminance);
  78542. lastTime = time;
  78543. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  78544. };
  78545. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  78546. };
  78547. // Create lens flare post-process
  78548. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  78549. var _this = this;
  78550. 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);
  78551. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  78552. this._createBlurPostProcesses(scene, ratio / 4, 2);
  78553. 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);
  78554. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  78555. var resolution = new BABYLON.Vector2(0, 0);
  78556. // Lens flare
  78557. this.lensFlarePostProcess.onApply = function (effect) {
  78558. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  78559. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  78560. effect.setFloat("strength", _this.lensFlareStrength);
  78561. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  78562. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  78563. // Shift
  78564. resolution.x = _this.lensFlarePostProcess.width;
  78565. resolution.y = _this.lensFlarePostProcess.height;
  78566. effect.setVector2("resolution", resolution);
  78567. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  78568. };
  78569. // Compose
  78570. 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);
  78571. 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);
  78572. this.lensFlareComposePostProcess.onApply = function (effect) {
  78573. if (!_this._scene.activeCamera) {
  78574. return;
  78575. }
  78576. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  78577. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  78578. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  78579. // Lens start rotation matrix
  78580. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  78581. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  78582. 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));
  78583. camRot *= 4.0;
  78584. 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);
  78585. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  78586. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  78587. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  78588. };
  78589. };
  78590. // Create depth-of-field post-process
  78591. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  78592. var _this = this;
  78593. 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);
  78594. this.depthOfFieldPostProcess.onApply = function (effect) {
  78595. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  78596. effect.setTexture("depthSampler", _this._getDepthTexture());
  78597. effect.setFloat("distance", _this.depthOfFieldDistance);
  78598. };
  78599. // Add to pipeline
  78600. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  78601. };
  78602. // Create motion blur post-process
  78603. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  78604. var _this = this;
  78605. 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);
  78606. var motionScale = 0;
  78607. var prevViewProjection = BABYLON.Matrix.Identity();
  78608. var invViewProjection = BABYLON.Matrix.Identity();
  78609. var viewProjection = BABYLON.Matrix.Identity();
  78610. var screenSize = BABYLON.Vector2.Zero();
  78611. this.motionBlurPostProcess.onApply = function (effect) {
  78612. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  78613. viewProjection.invertToRef(invViewProjection);
  78614. effect.setMatrix("inverseViewProjection", invViewProjection);
  78615. effect.setMatrix("prevViewProjection", prevViewProjection);
  78616. prevViewProjection = viewProjection;
  78617. screenSize.x = _this.motionBlurPostProcess.width;
  78618. screenSize.y = _this.motionBlurPostProcess.height;
  78619. effect.setVector2("screenSize", screenSize);
  78620. motionScale = scene.getEngine().getFps() / 60.0;
  78621. effect.setFloat("motionScale", motionScale);
  78622. effect.setFloat("motionStrength", _this.motionStrength);
  78623. effect.setTexture("depthSampler", _this._getDepthTexture());
  78624. };
  78625. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  78626. };
  78627. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  78628. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  78629. var renderer = this._scene.enableGeometryBufferRenderer();
  78630. return renderer.getGBuffer().textures[0];
  78631. }
  78632. return this._scene.enableDepthRenderer().getDepthMap();
  78633. };
  78634. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  78635. for (var i = 0; i < this._cameras.length; i++) {
  78636. var camera = this._cameras[i];
  78637. if (this.originalPostProcess) {
  78638. this.originalPostProcess.dispose(camera);
  78639. }
  78640. if (this.downSampleX4PostProcess) {
  78641. this.downSampleX4PostProcess.dispose(camera);
  78642. }
  78643. if (this.brightPassPostProcess) {
  78644. this.brightPassPostProcess.dispose(camera);
  78645. }
  78646. if (this.textureAdderPostProcess) {
  78647. this.textureAdderPostProcess.dispose(camera);
  78648. }
  78649. if (this.textureAdderFinalPostProcess) {
  78650. this.textureAdderFinalPostProcess.dispose(camera);
  78651. }
  78652. if (this.volumetricLightPostProcess) {
  78653. this.volumetricLightPostProcess.dispose(camera);
  78654. }
  78655. if (this.volumetricLightSmoothXPostProcess) {
  78656. this.volumetricLightSmoothXPostProcess.dispose(camera);
  78657. }
  78658. if (this.volumetricLightSmoothYPostProcess) {
  78659. this.volumetricLightSmoothYPostProcess.dispose(camera);
  78660. }
  78661. if (this.volumetricLightMergePostProces) {
  78662. this.volumetricLightMergePostProces.dispose(camera);
  78663. }
  78664. if (this.volumetricLightFinalPostProcess) {
  78665. this.volumetricLightFinalPostProcess.dispose(camera);
  78666. }
  78667. if (this.lensFlarePostProcess) {
  78668. this.lensFlarePostProcess.dispose(camera);
  78669. }
  78670. if (this.lensFlareComposePostProcess) {
  78671. this.lensFlareComposePostProcess.dispose(camera);
  78672. }
  78673. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  78674. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  78675. }
  78676. if (this.luminancePostProcess) {
  78677. this.luminancePostProcess.dispose(camera);
  78678. }
  78679. if (this.hdrPostProcess) {
  78680. this.hdrPostProcess.dispose(camera);
  78681. }
  78682. if (this.hdrFinalPostProcess) {
  78683. this.hdrFinalPostProcess.dispose(camera);
  78684. }
  78685. if (this.depthOfFieldPostProcess) {
  78686. this.depthOfFieldPostProcess.dispose(camera);
  78687. }
  78688. if (this.motionBlurPostProcess) {
  78689. this.motionBlurPostProcess.dispose(camera);
  78690. }
  78691. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  78692. this.blurHPostProcesses[j].dispose(camera);
  78693. }
  78694. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  78695. this.blurVPostProcesses[j].dispose(camera);
  78696. }
  78697. }
  78698. this.originalPostProcess = null;
  78699. this.downSampleX4PostProcess = null;
  78700. this.brightPassPostProcess = null;
  78701. this.textureAdderPostProcess = null;
  78702. this.textureAdderFinalPostProcess = null;
  78703. this.volumetricLightPostProcess = null;
  78704. this.volumetricLightSmoothXPostProcess = null;
  78705. this.volumetricLightSmoothYPostProcess = null;
  78706. this.volumetricLightMergePostProces = null;
  78707. this.volumetricLightFinalPostProcess = null;
  78708. this.lensFlarePostProcess = null;
  78709. this.lensFlareComposePostProcess = null;
  78710. this.luminancePostProcess = null;
  78711. this.hdrPostProcess = null;
  78712. this.hdrFinalPostProcess = null;
  78713. this.depthOfFieldPostProcess = null;
  78714. this.motionBlurPostProcess = null;
  78715. this.luminanceDownSamplePostProcesses = [];
  78716. this.blurHPostProcesses = [];
  78717. this.blurVPostProcesses = [];
  78718. };
  78719. /**
  78720. * Dispose of the pipeline and stop all post processes
  78721. */
  78722. StandardRenderingPipeline.prototype.dispose = function () {
  78723. this._disposePostProcesses();
  78724. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  78725. _super.prototype.dispose.call(this);
  78726. };
  78727. /**
  78728. * Serialize the rendering pipeline (Used when exporting)
  78729. * @returns the serialized object
  78730. */
  78731. StandardRenderingPipeline.prototype.serialize = function () {
  78732. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  78733. if (this.sourceLight) {
  78734. serializationObject.sourceLightId = this.sourceLight.id;
  78735. }
  78736. serializationObject.customType = "StandardRenderingPipeline";
  78737. return serializationObject;
  78738. };
  78739. /**
  78740. * Parse the serialized pipeline
  78741. * @param source Source pipeline.
  78742. * @param scene The scene to load the pipeline to.
  78743. * @param rootUrl The URL of the serialized pipeline.
  78744. * @returns An instantiated pipeline from the serialized object.
  78745. */
  78746. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  78747. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  78748. if (source.sourceLightId) {
  78749. p.sourceLight = scene.getLightByID(source.sourceLightId);
  78750. }
  78751. return p;
  78752. };
  78753. // Luminance steps
  78754. StandardRenderingPipeline.LuminanceSteps = 6;
  78755. __decorate([
  78756. BABYLON.serialize()
  78757. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  78758. __decorate([
  78759. BABYLON.serialize()
  78760. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  78761. __decorate([
  78762. BABYLON.serialize()
  78763. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  78764. __decorate([
  78765. BABYLON.serialize()
  78766. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  78767. __decorate([
  78768. BABYLON.serializeAsTexture("lensTexture")
  78769. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  78770. __decorate([
  78771. BABYLON.serialize()
  78772. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  78773. __decorate([
  78774. BABYLON.serialize()
  78775. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  78776. __decorate([
  78777. BABYLON.serialize()
  78778. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  78779. __decorate([
  78780. BABYLON.serialize()
  78781. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  78782. __decorate([
  78783. BABYLON.serialize()
  78784. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  78785. __decorate([
  78786. BABYLON.serialize()
  78787. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  78788. __decorate([
  78789. BABYLON.serializeAsTexture("lensColorTexture")
  78790. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  78791. __decorate([
  78792. BABYLON.serialize()
  78793. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  78794. __decorate([
  78795. BABYLON.serialize()
  78796. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  78797. __decorate([
  78798. BABYLON.serialize()
  78799. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  78800. __decorate([
  78801. BABYLON.serialize()
  78802. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  78803. __decorate([
  78804. BABYLON.serializeAsTexture("lensStarTexture")
  78805. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  78806. __decorate([
  78807. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  78808. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  78809. __decorate([
  78810. BABYLON.serialize()
  78811. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  78812. __decorate([
  78813. BABYLON.serialize()
  78814. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  78815. __decorate([
  78816. BABYLON.serialize()
  78817. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  78818. __decorate([
  78819. BABYLON.serialize()
  78820. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  78821. __decorate([
  78822. BABYLON.serialize()
  78823. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  78824. __decorate([
  78825. BABYLON.serialize()
  78826. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  78827. __decorate([
  78828. BABYLON.serialize()
  78829. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  78830. __decorate([
  78831. BABYLON.serialize()
  78832. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  78833. __decorate([
  78834. BABYLON.serialize()
  78835. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  78836. __decorate([
  78837. BABYLON.serialize()
  78838. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  78839. __decorate([
  78840. BABYLON.serialize()
  78841. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  78842. __decorate([
  78843. BABYLON.serialize()
  78844. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  78845. return StandardRenderingPipeline;
  78846. }(BABYLON.PostProcessRenderPipeline));
  78847. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  78848. })(BABYLON || (BABYLON = {}));
  78849. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  78850. var BABYLON;
  78851. (function (BABYLON) {
  78852. var FxaaPostProcess = /** @class */ (function (_super) {
  78853. __extends(FxaaPostProcess, _super);
  78854. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  78855. if (camera === void 0) { camera = null; }
  78856. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78857. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  78858. var defines = _this._getDefines();
  78859. _this.updateEffect(defines);
  78860. _this.onApplyObservable.add(function (effect) {
  78861. var texelSize = _this.texelSize;
  78862. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  78863. });
  78864. return _this;
  78865. }
  78866. FxaaPostProcess.prototype._getDefines = function () {
  78867. var engine = this.getEngine();
  78868. if (!engine) {
  78869. return null;
  78870. }
  78871. var glInfo = engine.getGlInfo();
  78872. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  78873. return "#define MALI 1\n";
  78874. }
  78875. return null;
  78876. };
  78877. return FxaaPostProcess;
  78878. }(BABYLON.PostProcess));
  78879. BABYLON.FxaaPostProcess = FxaaPostProcess;
  78880. })(BABYLON || (BABYLON = {}));
  78881. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  78882. var BABYLON;
  78883. (function (BABYLON) {
  78884. /**
  78885. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  78886. */
  78887. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  78888. __extends(ChromaticAberrationPostProcess, _super);
  78889. /**
  78890. * Creates a new instance ChromaticAberrationPostProcess
  78891. * @param name The name of the effect.
  78892. * @param screenWidth The width of the screen to apply the effect on.
  78893. * @param screenHeight The height of the screen to apply the effect on.
  78894. * @param options The required width/height ratio to downsize to before computing the render pass.
  78895. * @param camera The camera to apply the render pass to.
  78896. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78897. * @param engine The engine which the post process will be applied. (default: current engine)
  78898. * @param reusable If the post process can be reused on the same frame. (default: false)
  78899. * @param textureType Type of textures used when performing the post process. (default: 0)
  78900. * @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)
  78901. */
  78902. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78903. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78904. if (blockCompilation === void 0) { blockCompilation = false; }
  78905. 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;
  78906. /**
  78907. * The amount of seperation of rgb channels (default: 30)
  78908. */
  78909. _this.aberrationAmount = 30;
  78910. /**
  78911. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  78912. */
  78913. _this.radialIntensity = 0;
  78914. /**
  78915. * 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))
  78916. */
  78917. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  78918. /**
  78919. * 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))
  78920. */
  78921. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  78922. _this.onApplyObservable.add(function (effect) {
  78923. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  78924. effect.setFloat('screen_width', screenWidth);
  78925. effect.setFloat('screen_height', screenHeight);
  78926. effect.setFloat('radialIntensity', _this.radialIntensity);
  78927. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  78928. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  78929. });
  78930. return _this;
  78931. }
  78932. return ChromaticAberrationPostProcess;
  78933. }(BABYLON.PostProcess));
  78934. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  78935. })(BABYLON || (BABYLON = {}));
  78936. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  78937. var BABYLON;
  78938. (function (BABYLON) {
  78939. /**
  78940. * The GrainPostProcess adds noise to the image at mid luminance levels
  78941. */
  78942. var GrainPostProcess = /** @class */ (function (_super) {
  78943. __extends(GrainPostProcess, _super);
  78944. /**
  78945. * Creates a new instance of @see GrainPostProcess
  78946. * @param name The name of the effect.
  78947. * @param options The required width/height ratio to downsize to before computing the render pass.
  78948. * @param camera The camera to apply the render pass to.
  78949. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78950. * @param engine The engine which the post process will be applied. (default: current engine)
  78951. * @param reusable If the post process can be reused on the same frame. (default: false)
  78952. * @param textureType Type of textures used when performing the post process. (default: 0)
  78953. * @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)
  78954. */
  78955. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78956. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78957. if (blockCompilation === void 0) { blockCompilation = false; }
  78958. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  78959. /**
  78960. * The intensity of the grain added (default: 30)
  78961. */
  78962. _this.intensity = 30;
  78963. /**
  78964. * If the grain should be randomized on every frame
  78965. */
  78966. _this.animated = false;
  78967. _this.onApplyObservable.add(function (effect) {
  78968. effect.setFloat('intensity', _this.intensity);
  78969. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  78970. });
  78971. return _this;
  78972. }
  78973. return GrainPostProcess;
  78974. }(BABYLON.PostProcess));
  78975. BABYLON.GrainPostProcess = GrainPostProcess;
  78976. })(BABYLON || (BABYLON = {}));
  78977. //# sourceMappingURL=babylon.grainPostProcess.js.map
  78978. var BABYLON;
  78979. (function (BABYLON) {
  78980. /**
  78981. * The SharpenPostProcess applies a sharpen kernel to every pixel
  78982. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  78983. */
  78984. var SharpenPostProcess = /** @class */ (function (_super) {
  78985. __extends(SharpenPostProcess, _super);
  78986. /**
  78987. * Creates a new instance ConvolutionPostProcess
  78988. * @param name The name of the effect.
  78989. * @param options The required width/height ratio to downsize to before computing the render pass.
  78990. * @param camera The camera to apply the render pass to.
  78991. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78992. * @param engine The engine which the post process will be applied. (default: current engine)
  78993. * @param reusable If the post process can be reused on the same frame. (default: false)
  78994. * @param textureType Type of textures used when performing the post process. (default: 0)
  78995. * @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)
  78996. */
  78997. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78998. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78999. if (blockCompilation === void 0) { blockCompilation = false; }
  79000. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  79001. /**
  79002. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  79003. */
  79004. _this.colorAmount = 1.0;
  79005. /**
  79006. * How much sharpness should be applied (default: 0.3)
  79007. */
  79008. _this.edgeAmount = 0.3;
  79009. _this.onApply = function (effect) {
  79010. effect.setFloat2("screenSize", _this.width, _this.height);
  79011. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  79012. };
  79013. return _this;
  79014. }
  79015. return SharpenPostProcess;
  79016. }(BABYLON.PostProcess));
  79017. BABYLON.SharpenPostProcess = SharpenPostProcess;
  79018. })(BABYLON || (BABYLON = {}));
  79019. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  79020. var BABYLON;
  79021. (function (BABYLON) {
  79022. /**
  79023. * The Blur Post Process which blurs an image based on a kernel and direction.
  79024. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  79025. */
  79026. var BlurPostProcess = /** @class */ (function (_super) {
  79027. __extends(BlurPostProcess, _super);
  79028. /**
  79029. * Creates a new instance BlurPostProcess
  79030. * @param name The name of the effect.
  79031. * @param direction The direction in which to blur the image.
  79032. * @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.
  79033. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  79034. * @param camera The camera to apply the render pass to.
  79035. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79036. * @param engine The engine which the post process will be applied. (default: current engine)
  79037. * @param reusable If the post process can be reused on the same frame. (default: false)
  79038. * @param textureType Type of textures used when performing the post process. (default: 0)
  79039. * @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)
  79040. */
  79041. function BlurPostProcess(name,
  79042. /** The direction in which to blur the image. */
  79043. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  79044. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79045. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79046. if (defines === void 0) { defines = ""; }
  79047. if (blockCompilation === void 0) { blockCompilation = false; }
  79048. 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;
  79049. _this.direction = direction;
  79050. _this.blockCompilation = blockCompilation;
  79051. _this._packedFloat = false;
  79052. _this._staticDefines = "";
  79053. _this._staticDefines = defines;
  79054. _this.onApplyObservable.add(function (effect) {
  79055. if (_this._outputTexture) {
  79056. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  79057. }
  79058. else {
  79059. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  79060. }
  79061. });
  79062. _this.kernel = kernel;
  79063. return _this;
  79064. }
  79065. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  79066. /**
  79067. * Gets the length in pixels of the blur sample region
  79068. */
  79069. get: function () {
  79070. return this._idealKernel;
  79071. },
  79072. /**
  79073. * Sets the length in pixels of the blur sample region
  79074. */
  79075. set: function (v) {
  79076. if (this._idealKernel === v) {
  79077. return;
  79078. }
  79079. v = Math.max(v, 1);
  79080. this._idealKernel = v;
  79081. this._kernel = this._nearestBestKernel(v);
  79082. if (!this.blockCompilation) {
  79083. this._updateParameters();
  79084. }
  79085. },
  79086. enumerable: true,
  79087. configurable: true
  79088. });
  79089. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  79090. /**
  79091. * Gets wether or not the blur is unpacking/repacking floats
  79092. */
  79093. get: function () {
  79094. return this._packedFloat;
  79095. },
  79096. /**
  79097. * Sets wether or not the blur needs to unpack/repack floats
  79098. */
  79099. set: function (v) {
  79100. if (this._packedFloat === v) {
  79101. return;
  79102. }
  79103. this._packedFloat = v;
  79104. if (!this.blockCompilation) {
  79105. this._updateParameters();
  79106. }
  79107. },
  79108. enumerable: true,
  79109. configurable: true
  79110. });
  79111. /**
  79112. * Updates the effect with the current post process compile time values and recompiles the shader.
  79113. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  79114. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  79115. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  79116. * @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
  79117. * @param onCompiled Called when the shader has been compiled.
  79118. * @param onError Called if there is an error when compiling a shader.
  79119. */
  79120. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  79121. if (defines === void 0) { defines = null; }
  79122. if (uniforms === void 0) { uniforms = null; }
  79123. if (samplers === void 0) { samplers = null; }
  79124. this._updateParameters(onCompiled, onError);
  79125. };
  79126. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  79127. // Generate sampling offsets and weights
  79128. var N = this._kernel;
  79129. var centerIndex = (N - 1) / 2;
  79130. // Generate Gaussian sampling weights over kernel
  79131. var offsets = [];
  79132. var weights = [];
  79133. var totalWeight = 0;
  79134. for (var i = 0; i < N; i++) {
  79135. var u = i / (N - 1);
  79136. var w = this._gaussianWeight(u * 2.0 - 1);
  79137. offsets[i] = (i - centerIndex);
  79138. weights[i] = w;
  79139. totalWeight += w;
  79140. }
  79141. // Normalize weights
  79142. for (var i = 0; i < weights.length; i++) {
  79143. weights[i] /= totalWeight;
  79144. }
  79145. // Optimize: combine samples to take advantage of hardware linear sampling
  79146. // Walk from left to center, combining pairs (symmetrically)
  79147. var linearSamplingWeights = [];
  79148. var linearSamplingOffsets = [];
  79149. var linearSamplingMap = [];
  79150. for (var i = 0; i <= centerIndex; i += 2) {
  79151. var j = Math.min(i + 1, Math.floor(centerIndex));
  79152. var singleCenterSample = i === j;
  79153. if (singleCenterSample) {
  79154. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  79155. }
  79156. else {
  79157. var sharedCell = j === centerIndex;
  79158. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  79159. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  79160. if (offsetLinear === 0) {
  79161. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  79162. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  79163. }
  79164. else {
  79165. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  79166. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  79167. }
  79168. }
  79169. }
  79170. for (var i = 0; i < linearSamplingMap.length; i++) {
  79171. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  79172. linearSamplingWeights[i] = linearSamplingMap[i].w;
  79173. }
  79174. // Replace with optimized
  79175. offsets = linearSamplingOffsets;
  79176. weights = linearSamplingWeights;
  79177. // Generate shaders
  79178. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  79179. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  79180. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  79181. var defines = "";
  79182. defines += this._staticDefines;
  79183. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  79184. if (this._staticDefines.indexOf("DOF") != -1) {
  79185. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  79186. varyingCount--;
  79187. }
  79188. for (var i = 0; i < varyingCount; i++) {
  79189. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  79190. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  79191. }
  79192. var depCount = 0;
  79193. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  79194. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  79195. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  79196. depCount++;
  79197. }
  79198. if (this.packedFloat) {
  79199. defines += "#define PACKEDFLOAT 1";
  79200. }
  79201. this.blockCompilation = false;
  79202. _super.prototype.updateEffect.call(this, defines, null, null, {
  79203. varyingCount: varyingCount,
  79204. depCount: depCount
  79205. }, onCompiled, onError);
  79206. };
  79207. /**
  79208. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  79209. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  79210. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  79211. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  79212. * The gaps between physical kernels are compensated for in the weighting of the samples
  79213. * @param idealKernel Ideal blur kernel.
  79214. * @return Nearest best kernel.
  79215. */
  79216. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  79217. var v = Math.round(idealKernel);
  79218. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  79219. var k = _a[_i];
  79220. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  79221. return Math.max(k, 3);
  79222. }
  79223. }
  79224. return Math.max(v, 3);
  79225. };
  79226. /**
  79227. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  79228. * @param x The point on the Gaussian distribution to sample.
  79229. * @return the value of the Gaussian function at x.
  79230. */
  79231. BlurPostProcess.prototype._gaussianWeight = function (x) {
  79232. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  79233. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  79234. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  79235. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  79236. // truncated at around 1.3% of peak strength.
  79237. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  79238. var sigma = (1 / 3);
  79239. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  79240. var exponent = -((x * x) / (2.0 * sigma * sigma));
  79241. var weight = (1.0 / denominator) * Math.exp(exponent);
  79242. return weight;
  79243. };
  79244. /**
  79245. * Generates a string that can be used as a floating point number in GLSL.
  79246. * @param x Value to print.
  79247. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  79248. * @return GLSL float string.
  79249. */
  79250. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  79251. if (decimalFigures === void 0) { decimalFigures = 8; }
  79252. return x.toFixed(decimalFigures).replace(/0+$/, '');
  79253. };
  79254. return BlurPostProcess;
  79255. }(BABYLON.PostProcess));
  79256. BABYLON.BlurPostProcess = BlurPostProcess;
  79257. })(BABYLON || (BABYLON = {}));
  79258. //# sourceMappingURL=babylon.blurPostProcess.js.map
  79259. var BABYLON;
  79260. (function (BABYLON) {
  79261. /**
  79262. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  79263. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  79264. * based on samples that have a large difference in distance than the center pixel.
  79265. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  79266. */
  79267. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  79268. __extends(DepthOfFieldBlurPostProcess, _super);
  79269. /**
  79270. * Creates a new instance CircleOfConfusionPostProcess
  79271. * @param name The name of the effect.
  79272. * @param scene The scene the effect belongs to.
  79273. * @param direction The direction the blur should be applied.
  79274. * @param kernel The size of the kernel used to blur.
  79275. * @param options The required width/height ratio to downsize to before computing the render pass.
  79276. * @param camera The camera to apply the render pass to.
  79277. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  79278. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  79279. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79280. * @param engine The engine which the post process will be applied. (default: current engine)
  79281. * @param reusable If the post process can be reused on the same frame. (default: false)
  79282. * @param textureType Type of textures used when performing the post process. (default: 0)
  79283. * @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)
  79284. */
  79285. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  79286. if (imageToBlur === void 0) { imageToBlur = null; }
  79287. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79288. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79289. if (blockCompilation === void 0) { blockCompilation = false; }
  79290. 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;
  79291. _this.direction = direction;
  79292. _this.onApplyObservable.add(function (effect) {
  79293. if (imageToBlur != null) {
  79294. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  79295. }
  79296. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  79297. if (scene.activeCamera) {
  79298. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  79299. }
  79300. });
  79301. return _this;
  79302. }
  79303. return DepthOfFieldBlurPostProcess;
  79304. }(BABYLON.BlurPostProcess));
  79305. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  79306. })(BABYLON || (BABYLON = {}));
  79307. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  79308. var BABYLON;
  79309. (function (BABYLON) {
  79310. /**
  79311. * Options to be set when merging outputs from the default pipeline.
  79312. */
  79313. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  79314. function DepthOfFieldMergePostProcessOptions() {
  79315. }
  79316. return DepthOfFieldMergePostProcessOptions;
  79317. }());
  79318. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  79319. /**
  79320. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  79321. */
  79322. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  79323. __extends(DepthOfFieldMergePostProcess, _super);
  79324. /**
  79325. * Creates a new instance of DepthOfFieldMergePostProcess
  79326. * @param name The name of the effect.
  79327. * @param originalFromInput Post process which's input will be used for the merge.
  79328. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  79329. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  79330. * @param options The required width/height ratio to downsize to before computing the render pass.
  79331. * @param camera The camera to apply the render pass to.
  79332. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79333. * @param engine The engine which the post process will be applied. (default: current engine)
  79334. * @param reusable If the post process can be reused on the same frame. (default: false)
  79335. * @param textureType Type of textures used when performing the post process. (default: 0)
  79336. * @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)
  79337. */
  79338. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79339. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79340. if (blockCompilation === void 0) { blockCompilation = false; }
  79341. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  79342. _this.blurSteps = blurSteps;
  79343. _this.onApplyObservable.add(function (effect) {
  79344. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  79345. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  79346. blurSteps.forEach(function (step, index) {
  79347. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  79348. });
  79349. });
  79350. if (!blockCompilation) {
  79351. _this.updateEffect();
  79352. }
  79353. return _this;
  79354. }
  79355. /**
  79356. * Updates the effect with the current post process compile time values and recompiles the shader.
  79357. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  79358. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  79359. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  79360. * @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
  79361. * @param onCompiled Called when the shader has been compiled.
  79362. * @param onError Called if there is an error when compiling a shader.
  79363. */
  79364. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  79365. if (defines === void 0) { defines = null; }
  79366. if (uniforms === void 0) { uniforms = null; }
  79367. if (samplers === void 0) { samplers = null; }
  79368. if (!defines) {
  79369. defines = "";
  79370. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  79371. }
  79372. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  79373. };
  79374. return DepthOfFieldMergePostProcess;
  79375. }(BABYLON.PostProcess));
  79376. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  79377. })(BABYLON || (BABYLON = {}));
  79378. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  79379. var BABYLON;
  79380. (function (BABYLON) {
  79381. /**
  79382. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  79383. */
  79384. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  79385. __extends(CircleOfConfusionPostProcess, _super);
  79386. /**
  79387. * Creates a new instance CircleOfConfusionPostProcess
  79388. * @param name The name of the effect.
  79389. * @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.
  79390. * @param options The required width/height ratio to downsize to before computing the render pass.
  79391. * @param camera The camera to apply the render pass to.
  79392. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79393. * @param engine The engine which the post process will be applied. (default: current engine)
  79394. * @param reusable If the post process can be reused on the same frame. (default: false)
  79395. * @param textureType Type of textures used when performing the post process. (default: 0)
  79396. * @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)
  79397. */
  79398. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79399. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79400. if (blockCompilation === void 0) { blockCompilation = false; }
  79401. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  79402. /**
  79403. * 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.
  79404. */
  79405. _this.lensSize = 50;
  79406. /**
  79407. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  79408. */
  79409. _this.fStop = 1.4;
  79410. /**
  79411. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  79412. */
  79413. _this.focusDistance = 2000;
  79414. /**
  79415. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  79416. */
  79417. _this.focalLength = 50;
  79418. _this._depthTexture = null;
  79419. _this._depthTexture = depthTexture;
  79420. _this.onApplyObservable.add(function (effect) {
  79421. if (!_this._depthTexture) {
  79422. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  79423. return;
  79424. }
  79425. effect.setTexture("depthSampler", _this._depthTexture);
  79426. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  79427. var aperture = _this.lensSize / _this.fStop;
  79428. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  79429. effect.setFloat('focusDistance', _this.focusDistance);
  79430. effect.setFloat('cocPrecalculation', cocPrecalculation);
  79431. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  79432. });
  79433. return _this;
  79434. }
  79435. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  79436. /**
  79437. * 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.
  79438. */
  79439. set: function (value) {
  79440. this._depthTexture = value;
  79441. },
  79442. enumerable: true,
  79443. configurable: true
  79444. });
  79445. return CircleOfConfusionPostProcess;
  79446. }(BABYLON.PostProcess));
  79447. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  79448. })(BABYLON || (BABYLON = {}));
  79449. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  79450. var BABYLON;
  79451. (function (BABYLON) {
  79452. /**
  79453. * Specifies the level of max blur that should be applied when using the depth of field effect
  79454. */
  79455. var DepthOfFieldEffectBlurLevel;
  79456. (function (DepthOfFieldEffectBlurLevel) {
  79457. /**
  79458. * Subtle blur
  79459. */
  79460. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  79461. /**
  79462. * Medium blur
  79463. */
  79464. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  79465. /**
  79466. * Large blur
  79467. */
  79468. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  79469. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  79470. ;
  79471. /**
  79472. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  79473. */
  79474. var DepthOfFieldEffect = /** @class */ (function (_super) {
  79475. __extends(DepthOfFieldEffect, _super);
  79476. /**
  79477. * Creates a new instance DepthOfFieldEffect
  79478. * @param scene The scene the effect belongs to.
  79479. * @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.
  79480. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  79481. * @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)
  79482. */
  79483. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  79484. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  79485. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  79486. if (blockCompilation === void 0) { blockCompilation = false; }
  79487. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  79488. return _this._effects;
  79489. }, true) || this;
  79490. /**
  79491. * @hidden Internal post processes in depth of field effect
  79492. */
  79493. _this._effects = [];
  79494. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  79495. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79496. // 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)
  79497. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  79498. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  79499. _this._depthOfFieldBlurY = [];
  79500. _this._depthOfFieldBlurX = [];
  79501. var blurCount = 1;
  79502. var kernelSize = 15;
  79503. switch (blurLevel) {
  79504. case DepthOfFieldEffectBlurLevel.High: {
  79505. blurCount = 3;
  79506. kernelSize = 51;
  79507. break;
  79508. }
  79509. case DepthOfFieldEffectBlurLevel.Medium: {
  79510. blurCount = 2;
  79511. kernelSize = 31;
  79512. break;
  79513. }
  79514. default: {
  79515. kernelSize = 15;
  79516. blurCount = 1;
  79517. break;
  79518. }
  79519. }
  79520. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  79521. var ratio = 1.0;
  79522. for (var i = 0; i < blurCount; i++) {
  79523. 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);
  79524. blurY.autoClear = false;
  79525. ratio = 0.75 / Math.pow(2, i);
  79526. 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);
  79527. blurX.autoClear = false;
  79528. _this._depthOfFieldBlurY.push(blurY);
  79529. _this._depthOfFieldBlurX.push(blurX);
  79530. }
  79531. // Set all post processes on the effect.
  79532. _this._effects = [_this._circleOfConfusion];
  79533. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  79534. _this._effects.push(_this._depthOfFieldBlurY[i]);
  79535. _this._effects.push(_this._depthOfFieldBlurX[i]);
  79536. }
  79537. // Merge blurred images with original image based on circleOfConfusion
  79538. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79539. _this._dofMerge.autoClear = false;
  79540. _this._effects.push(_this._dofMerge);
  79541. return _this;
  79542. }
  79543. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  79544. get: function () {
  79545. return this._circleOfConfusion.focalLength;
  79546. },
  79547. /**
  79548. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  79549. */
  79550. set: function (value) {
  79551. this._circleOfConfusion.focalLength = value;
  79552. },
  79553. enumerable: true,
  79554. configurable: true
  79555. });
  79556. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  79557. get: function () {
  79558. return this._circleOfConfusion.fStop;
  79559. },
  79560. /**
  79561. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  79562. */
  79563. set: function (value) {
  79564. this._circleOfConfusion.fStop = value;
  79565. },
  79566. enumerable: true,
  79567. configurable: true
  79568. });
  79569. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  79570. get: function () {
  79571. return this._circleOfConfusion.focusDistance;
  79572. },
  79573. /**
  79574. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  79575. */
  79576. set: function (value) {
  79577. this._circleOfConfusion.focusDistance = value;
  79578. },
  79579. enumerable: true,
  79580. configurable: true
  79581. });
  79582. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  79583. get: function () {
  79584. return this._circleOfConfusion.lensSize;
  79585. },
  79586. /**
  79587. * 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.
  79588. */
  79589. set: function (value) {
  79590. this._circleOfConfusion.lensSize = value;
  79591. },
  79592. enumerable: true,
  79593. configurable: true
  79594. });
  79595. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  79596. /**
  79597. * 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.
  79598. */
  79599. set: function (value) {
  79600. this._circleOfConfusion.depthTexture = value;
  79601. },
  79602. enumerable: true,
  79603. configurable: true
  79604. });
  79605. /**
  79606. * Disposes each of the internal effects for a given camera.
  79607. * @param camera The camera to dispose the effect on.
  79608. */
  79609. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  79610. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79611. this._effects[effectIndex].dispose(camera);
  79612. }
  79613. };
  79614. /**
  79615. * @hidden Internal
  79616. */
  79617. DepthOfFieldEffect.prototype._updateEffects = function () {
  79618. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79619. this._effects[effectIndex].updateEffect();
  79620. }
  79621. };
  79622. /**
  79623. * Internal
  79624. * @returns if all the contained post processes are ready.
  79625. * @hidden
  79626. */
  79627. DepthOfFieldEffect.prototype._isReady = function () {
  79628. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79629. if (!this._effects[effectIndex].isReady()) {
  79630. return false;
  79631. }
  79632. }
  79633. return true;
  79634. };
  79635. return DepthOfFieldEffect;
  79636. }(BABYLON.PostProcessRenderEffect));
  79637. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  79638. })(BABYLON || (BABYLON = {}));
  79639. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  79640. var BABYLON;
  79641. (function (BABYLON) {
  79642. /**
  79643. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  79644. */
  79645. var BloomMergePostProcess = /** @class */ (function (_super) {
  79646. __extends(BloomMergePostProcess, _super);
  79647. /**
  79648. * Creates a new instance of @see BloomMergePostProcess
  79649. * @param name The name of the effect.
  79650. * @param originalFromInput Post process which's input will be used for the merge.
  79651. * @param blurred Blurred highlights post process which's output will be used.
  79652. * @param weight Weight of the bloom to be added to the original input.
  79653. * @param options The required width/height ratio to downsize to before computing the render pass.
  79654. * @param camera The camera to apply the render pass to.
  79655. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79656. * @param engine The engine which the post process will be applied. (default: current engine)
  79657. * @param reusable If the post process can be reused on the same frame. (default: false)
  79658. * @param textureType Type of textures used when performing the post process. (default: 0)
  79659. * @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)
  79660. */
  79661. function BloomMergePostProcess(name, originalFromInput, blurred,
  79662. /** Weight of the bloom to be added to the original input. */
  79663. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79664. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79665. if (blockCompilation === void 0) { blockCompilation = false; }
  79666. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  79667. _this.weight = weight;
  79668. _this.onApplyObservable.add(function (effect) {
  79669. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  79670. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  79671. effect.setFloat("bloomWeight", _this.weight);
  79672. });
  79673. if (!blockCompilation) {
  79674. _this.updateEffect();
  79675. }
  79676. return _this;
  79677. }
  79678. return BloomMergePostProcess;
  79679. }(BABYLON.PostProcess));
  79680. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  79681. })(BABYLON || (BABYLON = {}));
  79682. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  79683. var BABYLON;
  79684. (function (BABYLON) {
  79685. /**
  79686. * 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.
  79687. */
  79688. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  79689. __extends(ExtractHighlightsPostProcess, _super);
  79690. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79691. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79692. if (blockCompilation === void 0) { blockCompilation = false; }
  79693. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  79694. /**
  79695. * The luminance threshold, pixels below this value will be set to black.
  79696. */
  79697. _this.threshold = 0.9;
  79698. /** @hidden */
  79699. _this._exposure = 1;
  79700. /**
  79701. * Post process which has the input texture to be used when performing highlight extraction
  79702. * @hidden
  79703. */
  79704. _this._inputPostProcess = null;
  79705. _this.onApplyObservable.add(function (effect) {
  79706. if (_this._inputPostProcess) {
  79707. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  79708. }
  79709. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  79710. effect.setFloat('exposure', _this._exposure);
  79711. });
  79712. return _this;
  79713. }
  79714. return ExtractHighlightsPostProcess;
  79715. }(BABYLON.PostProcess));
  79716. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  79717. })(BABYLON || (BABYLON = {}));
  79718. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  79719. var BABYLON;
  79720. (function (BABYLON) {
  79721. /**
  79722. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  79723. */
  79724. var BloomEffect = /** @class */ (function (_super) {
  79725. __extends(BloomEffect, _super);
  79726. /**
  79727. * Creates a new instance of @see BloomEffect
  79728. * @param scene The scene the effect belongs to.
  79729. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  79730. * @param bloomKernel The size of the kernel to be used when applying the blur.
  79731. * @param bloomWeight The the strength of bloom.
  79732. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  79733. * @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)
  79734. */
  79735. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  79736. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  79737. if (blockCompilation === void 0) { blockCompilation = false; }
  79738. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  79739. return _this._effects;
  79740. }, true) || this;
  79741. _this.bloomScale = bloomScale;
  79742. /**
  79743. * @hidden Internal
  79744. */
  79745. _this._effects = [];
  79746. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79747. _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);
  79748. _this._blurX.alwaysForcePOT = true;
  79749. _this._blurX.autoClear = false;
  79750. _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);
  79751. _this._blurY.alwaysForcePOT = true;
  79752. _this._blurY.autoClear = false;
  79753. _this.kernel = bloomKernel;
  79754. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  79755. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79756. _this._merge.autoClear = false;
  79757. _this._effects.push(_this._merge);
  79758. return _this;
  79759. }
  79760. Object.defineProperty(BloomEffect.prototype, "threshold", {
  79761. /**
  79762. * The luminance threshold to find bright areas of the image to bloom.
  79763. */
  79764. get: function () {
  79765. return this._downscale.threshold;
  79766. },
  79767. set: function (value) {
  79768. this._downscale.threshold = value;
  79769. },
  79770. enumerable: true,
  79771. configurable: true
  79772. });
  79773. Object.defineProperty(BloomEffect.prototype, "weight", {
  79774. /**
  79775. * The strength of the bloom.
  79776. */
  79777. get: function () {
  79778. return this._merge.weight;
  79779. },
  79780. set: function (value) {
  79781. this._merge.weight = value;
  79782. },
  79783. enumerable: true,
  79784. configurable: true
  79785. });
  79786. Object.defineProperty(BloomEffect.prototype, "kernel", {
  79787. /**
  79788. * Specifies the size of the bloom blur kernel, relative to the final output size
  79789. */
  79790. get: function () {
  79791. return this._blurX.kernel / this.bloomScale;
  79792. },
  79793. set: function (value) {
  79794. this._blurX.kernel = value * this.bloomScale;
  79795. this._blurY.kernel = value * this.bloomScale;
  79796. },
  79797. enumerable: true,
  79798. configurable: true
  79799. });
  79800. /**
  79801. * Disposes each of the internal effects for a given camera.
  79802. * @param camera The camera to dispose the effect on.
  79803. */
  79804. BloomEffect.prototype.disposeEffects = function (camera) {
  79805. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79806. this._effects[effectIndex].dispose(camera);
  79807. }
  79808. };
  79809. /**
  79810. * @hidden Internal
  79811. */
  79812. BloomEffect.prototype._updateEffects = function () {
  79813. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79814. this._effects[effectIndex].updateEffect();
  79815. }
  79816. };
  79817. /**
  79818. * Internal
  79819. * @returns if all the contained post processes are ready.
  79820. * @hidden
  79821. */
  79822. BloomEffect.prototype._isReady = function () {
  79823. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79824. if (!this._effects[effectIndex].isReady()) {
  79825. return false;
  79826. }
  79827. }
  79828. return true;
  79829. };
  79830. return BloomEffect;
  79831. }(BABYLON.PostProcessRenderEffect));
  79832. BABYLON.BloomEffect = BloomEffect;
  79833. })(BABYLON || (BABYLON = {}));
  79834. //# sourceMappingURL=babylon.bloomEffect.js.map
  79835. var BABYLON;
  79836. (function (BABYLON) {
  79837. /**
  79838. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  79839. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  79840. */
  79841. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  79842. __extends(DefaultRenderingPipeline, _super);
  79843. /**
  79844. * @constructor
  79845. * @param {string} name - The rendering pipeline name (default: "")
  79846. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  79847. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  79848. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  79849. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  79850. */
  79851. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  79852. if (name === void 0) { name = ""; }
  79853. if (hdr === void 0) { hdr = true; }
  79854. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  79855. if (automaticBuild === void 0) { automaticBuild = true; }
  79856. var _this = _super.call(this, scene.getEngine(), name) || this;
  79857. _this._camerasToBeAttached = [];
  79858. /**
  79859. * ID of the sharpen post process,
  79860. */
  79861. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  79862. /**
  79863. * ID of the image processing post process;
  79864. */
  79865. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  79866. /**
  79867. * ID of the Fast Approximate Anti-Aliasing post process;
  79868. */
  79869. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  79870. /**
  79871. * ID of the chromatic aberration post process,
  79872. */
  79873. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  79874. /**
  79875. * ID of the grain post process
  79876. */
  79877. _this.GrainPostProcessId = "GrainPostProcessEffect";
  79878. /**
  79879. * Glow post process which adds a glow to emmisive areas of the image
  79880. */
  79881. _this._glowLayer = null;
  79882. /**
  79883. * Animations which can be used to tweak settings over a period of time
  79884. */
  79885. _this.animations = [];
  79886. _this._imageProcessingConfigurationObserver = null;
  79887. // Values
  79888. _this._sharpenEnabled = false;
  79889. _this._bloomEnabled = false;
  79890. _this._depthOfFieldEnabled = false;
  79891. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  79892. _this._fxaaEnabled = false;
  79893. _this._imageProcessingEnabled = true;
  79894. _this._bloomScale = 0.5;
  79895. _this._chromaticAberrationEnabled = false;
  79896. _this._grainEnabled = false;
  79897. _this._buildAllowed = true;
  79898. _this._resizeObserver = null;
  79899. _this._hardwareScaleLevel = 1.0;
  79900. _this._bloomKernel = 64;
  79901. /**
  79902. * Specifies the weight of the bloom in the final rendering
  79903. */
  79904. _this._bloomWeight = 0.15;
  79905. /**
  79906. * Specifies the luma threshold for the area that will be blurred by the bloom
  79907. */
  79908. _this._bloomThreshold = 0.9;
  79909. _this._samples = 1;
  79910. _this._hasCleared = false;
  79911. _this._prevPostProcess = null;
  79912. _this._prevPrevPostProcess = null;
  79913. _this._cameras = cameras || scene.cameras;
  79914. _this._cameras = _this._cameras.slice();
  79915. _this._camerasToBeAttached = _this._cameras.slice();
  79916. _this._buildAllowed = automaticBuild;
  79917. // Initialize
  79918. _this._scene = scene;
  79919. var caps = _this._scene.getEngine().getCaps();
  79920. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  79921. // Misc
  79922. if (_this._hdr) {
  79923. if (caps.textureHalfFloatRender) {
  79924. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79925. }
  79926. else if (caps.textureFloatRender) {
  79927. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79928. }
  79929. }
  79930. else {
  79931. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79932. }
  79933. // Attach
  79934. scene.postProcessRenderPipelineManager.addPipeline(_this);
  79935. var engine = _this._scene.getEngine();
  79936. // Create post processes before hand so they can be modified before enabled.
  79937. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  79938. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  79939. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  79940. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  79941. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  79942. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  79943. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  79944. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  79945. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  79946. _this._resizeObserver = engine.onResizeObservable.add(function () {
  79947. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  79948. _this.bloomKernel = _this.bloomKernel;
  79949. });
  79950. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  79951. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  79952. });
  79953. _this._buildPipeline();
  79954. return _this;
  79955. }
  79956. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  79957. get: function () {
  79958. return this._sharpenEnabled;
  79959. },
  79960. /**
  79961. * Enable or disable the sharpen process from the pipeline
  79962. */
  79963. set: function (enabled) {
  79964. if (this._sharpenEnabled === enabled) {
  79965. return;
  79966. }
  79967. this._sharpenEnabled = enabled;
  79968. this._buildPipeline();
  79969. },
  79970. enumerable: true,
  79971. configurable: true
  79972. });
  79973. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  79974. /**
  79975. * Specifies the size of the bloom blur kernel, relative to the final output size
  79976. */
  79977. get: function () {
  79978. return this._bloomKernel;
  79979. },
  79980. set: function (value) {
  79981. this._bloomKernel = value;
  79982. this.bloom.kernel = value / this._hardwareScaleLevel;
  79983. },
  79984. enumerable: true,
  79985. configurable: true
  79986. });
  79987. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  79988. get: function () {
  79989. return this._bloomWeight;
  79990. },
  79991. /**
  79992. * The strength of the bloom.
  79993. */
  79994. set: function (value) {
  79995. if (this._bloomWeight === value) {
  79996. return;
  79997. }
  79998. this.bloom.weight = value;
  79999. this._bloomWeight = value;
  80000. },
  80001. enumerable: true,
  80002. configurable: true
  80003. });
  80004. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  80005. get: function () {
  80006. return this._bloomThreshold;
  80007. },
  80008. /**
  80009. * The strength of the bloom.
  80010. */
  80011. set: function (value) {
  80012. if (this._bloomThreshold === value) {
  80013. return;
  80014. }
  80015. this.bloom.threshold = value;
  80016. this._bloomThreshold = value;
  80017. },
  80018. enumerable: true,
  80019. configurable: true
  80020. });
  80021. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  80022. get: function () {
  80023. return this._bloomScale;
  80024. },
  80025. /**
  80026. * The scale of the bloom, lower value will provide better performance.
  80027. */
  80028. set: function (value) {
  80029. if (this._bloomScale === value) {
  80030. return;
  80031. }
  80032. this._bloomScale = value;
  80033. // recreate bloom and dispose old as this setting is not dynamic
  80034. this._rebuildBloom();
  80035. this._buildPipeline();
  80036. },
  80037. enumerable: true,
  80038. configurable: true
  80039. });
  80040. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  80041. get: function () {
  80042. return this._bloomEnabled;
  80043. },
  80044. /**
  80045. * Enable or disable the bloom from the pipeline
  80046. */
  80047. set: function (enabled) {
  80048. if (this._bloomEnabled === enabled) {
  80049. return;
  80050. }
  80051. this._bloomEnabled = enabled;
  80052. this._buildPipeline();
  80053. },
  80054. enumerable: true,
  80055. configurable: true
  80056. });
  80057. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  80058. // recreate bloom and dispose old as this setting is not dynamic
  80059. var oldBloom = this.bloom;
  80060. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  80061. this.bloom.threshold = oldBloom.threshold;
  80062. for (var i = 0; i < this._cameras.length; i++) {
  80063. oldBloom.disposeEffects(this._cameras[i]);
  80064. }
  80065. };
  80066. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  80067. /**
  80068. * If the depth of field is enabled.
  80069. */
  80070. get: function () {
  80071. return this._depthOfFieldEnabled;
  80072. },
  80073. set: function (enabled) {
  80074. if (this._depthOfFieldEnabled === enabled) {
  80075. return;
  80076. }
  80077. this._depthOfFieldEnabled = enabled;
  80078. this._buildPipeline();
  80079. },
  80080. enumerable: true,
  80081. configurable: true
  80082. });
  80083. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  80084. /**
  80085. * Blur level of the depth of field effect. (Higher blur will effect performance)
  80086. */
  80087. get: function () {
  80088. return this._depthOfFieldBlurLevel;
  80089. },
  80090. set: function (value) {
  80091. if (this._depthOfFieldBlurLevel === value) {
  80092. return;
  80093. }
  80094. this._depthOfFieldBlurLevel = value;
  80095. // recreate dof and dispose old as this setting is not dynamic
  80096. var oldDof = this.depthOfField;
  80097. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  80098. this.depthOfField.focalLength = oldDof.focalLength;
  80099. this.depthOfField.focusDistance = oldDof.focusDistance;
  80100. this.depthOfField.fStop = oldDof.fStop;
  80101. this.depthOfField.lensSize = oldDof.lensSize;
  80102. for (var i = 0; i < this._cameras.length; i++) {
  80103. oldDof.disposeEffects(this._cameras[i]);
  80104. }
  80105. this._buildPipeline();
  80106. },
  80107. enumerable: true,
  80108. configurable: true
  80109. });
  80110. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  80111. get: function () {
  80112. return this._fxaaEnabled;
  80113. },
  80114. /**
  80115. * If the anti aliasing is enabled.
  80116. */
  80117. set: function (enabled) {
  80118. if (this._fxaaEnabled === enabled) {
  80119. return;
  80120. }
  80121. this._fxaaEnabled = enabled;
  80122. this._buildPipeline();
  80123. },
  80124. enumerable: true,
  80125. configurable: true
  80126. });
  80127. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  80128. get: function () {
  80129. return this._samples;
  80130. },
  80131. /**
  80132. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  80133. */
  80134. set: function (sampleCount) {
  80135. if (this._samples === sampleCount) {
  80136. return;
  80137. }
  80138. this._samples = sampleCount;
  80139. this._buildPipeline();
  80140. },
  80141. enumerable: true,
  80142. configurable: true
  80143. });
  80144. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  80145. get: function () {
  80146. return this._imageProcessingEnabled;
  80147. },
  80148. /**
  80149. * If image processing is enabled.
  80150. */
  80151. set: function (enabled) {
  80152. if (this._imageProcessingEnabled === enabled) {
  80153. return;
  80154. }
  80155. this._imageProcessingEnabled = enabled;
  80156. this._buildPipeline();
  80157. },
  80158. enumerable: true,
  80159. configurable: true
  80160. });
  80161. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  80162. get: function () {
  80163. return this._glowLayer == null;
  80164. },
  80165. /**
  80166. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  80167. */
  80168. set: function (enabled) {
  80169. if (enabled && !this._glowLayer) {
  80170. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  80171. }
  80172. else if (!enabled && this._glowLayer) {
  80173. this._glowLayer.dispose();
  80174. this._glowLayer = null;
  80175. }
  80176. },
  80177. enumerable: true,
  80178. configurable: true
  80179. });
  80180. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  80181. get: function () {
  80182. return this._chromaticAberrationEnabled;
  80183. },
  80184. /**
  80185. * Enable or disable the chromaticAberration process from the pipeline
  80186. */
  80187. set: function (enabled) {
  80188. if (this._chromaticAberrationEnabled === enabled) {
  80189. return;
  80190. }
  80191. this._chromaticAberrationEnabled = enabled;
  80192. this._buildPipeline();
  80193. },
  80194. enumerable: true,
  80195. configurable: true
  80196. });
  80197. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  80198. get: function () {
  80199. return this._grainEnabled;
  80200. },
  80201. /**
  80202. * Enable or disable the grain process from the pipeline
  80203. */
  80204. set: function (enabled) {
  80205. if (this._grainEnabled === enabled) {
  80206. return;
  80207. }
  80208. this._grainEnabled = enabled;
  80209. this._buildPipeline();
  80210. },
  80211. enumerable: true,
  80212. configurable: true
  80213. });
  80214. /**
  80215. * Force the compilation of the entire pipeline.
  80216. */
  80217. DefaultRenderingPipeline.prototype.prepare = function () {
  80218. var previousState = this._buildAllowed;
  80219. this._buildAllowed = true;
  80220. this._buildPipeline();
  80221. this._buildAllowed = previousState;
  80222. };
  80223. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  80224. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  80225. if (this._hasCleared) {
  80226. postProcess.autoClear = false;
  80227. }
  80228. else {
  80229. postProcess.autoClear = true;
  80230. this._scene.autoClear = false;
  80231. this._hasCleared = true;
  80232. }
  80233. if (!skipTextureSharing) {
  80234. if (this._prevPrevPostProcess) {
  80235. postProcess.shareOutputWith(this._prevPrevPostProcess);
  80236. }
  80237. else {
  80238. postProcess.useOwnOutput();
  80239. }
  80240. if (this._prevPostProcess) {
  80241. this._prevPrevPostProcess = this._prevPostProcess;
  80242. }
  80243. this._prevPostProcess = postProcess;
  80244. }
  80245. };
  80246. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  80247. var _this = this;
  80248. if (!this._buildAllowed) {
  80249. return;
  80250. }
  80251. this._scene.autoClear = true;
  80252. var engine = this._scene.getEngine();
  80253. this._disposePostProcesses();
  80254. if (this._cameras !== null) {
  80255. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  80256. // get back cameras to be used to reattach pipeline
  80257. this._cameras = this._camerasToBeAttached.slice();
  80258. }
  80259. this._reset();
  80260. this._prevPostProcess = null;
  80261. this._prevPrevPostProcess = null;
  80262. this._hasCleared = false;
  80263. if (this.depthOfFieldEnabled) {
  80264. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  80265. this.depthOfField.depthTexture = depthTexture;
  80266. if (!this.depthOfField._isReady()) {
  80267. this.depthOfField._updateEffects();
  80268. }
  80269. this.addEffect(this.depthOfField);
  80270. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  80271. }
  80272. if (this.bloomEnabled) {
  80273. if (!this.bloom._isReady()) {
  80274. this.bloom._updateEffects();
  80275. }
  80276. this.addEffect(this.bloom);
  80277. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  80278. }
  80279. if (this._imageProcessingEnabled) {
  80280. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  80281. if (this._hdr) {
  80282. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  80283. this._setAutoClearAndTextureSharing(this.imageProcessing);
  80284. }
  80285. else {
  80286. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  80287. }
  80288. }
  80289. if (this.sharpenEnabled) {
  80290. if (!this.sharpen.isReady()) {
  80291. this.sharpen.updateEffect();
  80292. }
  80293. this.addEffect(this._sharpenEffect);
  80294. this._setAutoClearAndTextureSharing(this.sharpen);
  80295. }
  80296. if (this.grainEnabled) {
  80297. if (!this.grain.isReady()) {
  80298. this.grain.updateEffect();
  80299. }
  80300. this.addEffect(this._grainEffect);
  80301. this._setAutoClearAndTextureSharing(this.grain);
  80302. }
  80303. if (this.chromaticAberrationEnabled) {
  80304. if (!this.chromaticAberration.isReady()) {
  80305. this.chromaticAberration.updateEffect();
  80306. }
  80307. this.addEffect(this._chromaticAberrationEffect);
  80308. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  80309. }
  80310. if (this.fxaaEnabled) {
  80311. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  80312. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  80313. this._setAutoClearAndTextureSharing(this.fxaa, true);
  80314. }
  80315. if (this._cameras !== null) {
  80316. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  80317. }
  80318. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  80319. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  80320. }
  80321. };
  80322. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  80323. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  80324. for (var i = 0; i < this._cameras.length; i++) {
  80325. var camera = this._cameras[i];
  80326. if (this.imageProcessing) {
  80327. this.imageProcessing.dispose(camera);
  80328. }
  80329. if (this.fxaa) {
  80330. this.fxaa.dispose(camera);
  80331. }
  80332. // These are created in the constructor and should not be disposed on every pipeline change
  80333. if (disposeNonRecreated) {
  80334. if (this.sharpen) {
  80335. this.sharpen.dispose(camera);
  80336. }
  80337. if (this.depthOfField) {
  80338. this.depthOfField.disposeEffects(camera);
  80339. }
  80340. if (this.bloom) {
  80341. this.bloom.disposeEffects(camera);
  80342. }
  80343. if (this.chromaticAberration) {
  80344. this.chromaticAberration.dispose(camera);
  80345. }
  80346. if (this.grain) {
  80347. this.grain.dispose(camera);
  80348. }
  80349. if (this._glowLayer) {
  80350. this._glowLayer.dispose();
  80351. }
  80352. }
  80353. }
  80354. this.imageProcessing = null;
  80355. this.fxaa = null;
  80356. if (disposeNonRecreated) {
  80357. this.sharpen = null;
  80358. this._sharpenEffect = null;
  80359. this.depthOfField = null;
  80360. this.bloom = null;
  80361. this.chromaticAberration = null;
  80362. this._chromaticAberrationEffect = null;
  80363. this.grain = null;
  80364. this._grainEffect = null;
  80365. this._glowLayer = null;
  80366. }
  80367. };
  80368. /**
  80369. * Adds a camera to the pipeline
  80370. * @param camera the camera to be added
  80371. */
  80372. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  80373. this._camerasToBeAttached.push(camera);
  80374. this._buildPipeline();
  80375. };
  80376. /**
  80377. * Removes a camera from the pipeline
  80378. * @param camera the camera to remove
  80379. */
  80380. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  80381. var index = this._camerasToBeAttached.indexOf(camera);
  80382. this._camerasToBeAttached.splice(index, 1);
  80383. this._buildPipeline();
  80384. };
  80385. /**
  80386. * Dispose of the pipeline and stop all post processes
  80387. */
  80388. DefaultRenderingPipeline.prototype.dispose = function () {
  80389. this._disposePostProcesses(true);
  80390. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  80391. this._scene.autoClear = true;
  80392. if (this._resizeObserver) {
  80393. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  80394. this._resizeObserver = null;
  80395. }
  80396. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  80397. _super.prototype.dispose.call(this);
  80398. };
  80399. /**
  80400. * Serialize the rendering pipeline (Used when exporting)
  80401. * @returns the serialized object
  80402. */
  80403. DefaultRenderingPipeline.prototype.serialize = function () {
  80404. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  80405. serializationObject.customType = "DefaultRenderingPipeline";
  80406. return serializationObject;
  80407. };
  80408. /**
  80409. * Parse the serialized pipeline
  80410. * @param source Source pipeline.
  80411. * @param scene The scene to load the pipeline to.
  80412. * @param rootUrl The URL of the serialized pipeline.
  80413. * @returns An instantiated pipeline from the serialized object.
  80414. */
  80415. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  80416. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  80417. };
  80418. __decorate([
  80419. BABYLON.serialize()
  80420. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  80421. __decorate([
  80422. BABYLON.serialize()
  80423. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  80424. __decorate([
  80425. BABYLON.serialize()
  80426. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  80427. __decorate([
  80428. BABYLON.serialize()
  80429. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  80430. __decorate([
  80431. BABYLON.serialize()
  80432. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  80433. __decorate([
  80434. BABYLON.serialize()
  80435. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  80436. __decorate([
  80437. BABYLON.serialize()
  80438. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  80439. __decorate([
  80440. BABYLON.serialize()
  80441. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  80442. __decorate([
  80443. BABYLON.serialize()
  80444. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  80445. __decorate([
  80446. BABYLON.serialize()
  80447. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  80448. __decorate([
  80449. BABYLON.serialize()
  80450. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  80451. __decorate([
  80452. BABYLON.serialize()
  80453. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  80454. __decorate([
  80455. BABYLON.serialize()
  80456. ], DefaultRenderingPipeline.prototype, "samples", null);
  80457. __decorate([
  80458. BABYLON.serialize()
  80459. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  80460. __decorate([
  80461. BABYLON.serialize()
  80462. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  80463. __decorate([
  80464. BABYLON.serialize()
  80465. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  80466. __decorate([
  80467. BABYLON.serialize()
  80468. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  80469. return DefaultRenderingPipeline;
  80470. }(BABYLON.PostProcessRenderPipeline));
  80471. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  80472. })(BABYLON || (BABYLON = {}));
  80473. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  80474. var BABYLON;
  80475. (function (BABYLON) {
  80476. /**
  80477. * @hidden
  80478. */
  80479. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  80480. __extends(ImageProcessingConfigurationDefines, _super);
  80481. function ImageProcessingConfigurationDefines() {
  80482. var _this = _super.call(this) || this;
  80483. _this.IMAGEPROCESSING = false;
  80484. _this.VIGNETTE = false;
  80485. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  80486. _this.VIGNETTEBLENDMODEOPAQUE = false;
  80487. _this.TONEMAPPING = false;
  80488. _this.TONEMAPPING_ACES = false;
  80489. _this.CONTRAST = false;
  80490. _this.COLORCURVES = false;
  80491. _this.COLORGRADING = false;
  80492. _this.COLORGRADING3D = false;
  80493. _this.SAMPLER3DGREENDEPTH = false;
  80494. _this.SAMPLER3DBGRMAP = false;
  80495. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  80496. _this.EXPOSURE = false;
  80497. _this.rebuild();
  80498. return _this;
  80499. }
  80500. return ImageProcessingConfigurationDefines;
  80501. }(BABYLON.MaterialDefines));
  80502. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  80503. /**
  80504. * This groups together the common properties used for image processing either in direct forward pass
  80505. * or through post processing effect depending on the use of the image processing pipeline in your scene
  80506. * or not.
  80507. */
  80508. var ImageProcessingConfiguration = /** @class */ (function () {
  80509. function ImageProcessingConfiguration() {
  80510. /**
  80511. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  80512. */
  80513. this.colorCurves = new BABYLON.ColorCurves();
  80514. this._colorCurvesEnabled = false;
  80515. this._colorGradingEnabled = false;
  80516. this._colorGradingWithGreenDepth = true;
  80517. this._colorGradingBGR = true;
  80518. /** @hidden */
  80519. this._exposure = 1.0;
  80520. this._toneMappingEnabled = false;
  80521. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  80522. this._contrast = 1.0;
  80523. /**
  80524. * Vignette stretch size.
  80525. */
  80526. this.vignetteStretch = 0;
  80527. /**
  80528. * Vignette centre X Offset.
  80529. */
  80530. this.vignetteCentreX = 0;
  80531. /**
  80532. * Vignette centre Y Offset.
  80533. */
  80534. this.vignetteCentreY = 0;
  80535. /**
  80536. * Vignette weight or intensity of the vignette effect.
  80537. */
  80538. this.vignetteWeight = 1.5;
  80539. /**
  80540. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  80541. * if vignetteEnabled is set to true.
  80542. */
  80543. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  80544. /**
  80545. * Camera field of view used by the Vignette effect.
  80546. */
  80547. this.vignetteCameraFov = 0.5;
  80548. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  80549. this._vignetteEnabled = false;
  80550. this._applyByPostProcess = false;
  80551. this._isEnabled = true;
  80552. /**
  80553. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  80554. */
  80555. this.onUpdateParameters = new BABYLON.Observable();
  80556. }
  80557. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  80558. /**
  80559. * Gets wether the color curves effect is enabled.
  80560. */
  80561. get: function () {
  80562. return this._colorCurvesEnabled;
  80563. },
  80564. /**
  80565. * Sets wether the color curves effect is enabled.
  80566. */
  80567. set: function (value) {
  80568. if (this._colorCurvesEnabled === value) {
  80569. return;
  80570. }
  80571. this._colorCurvesEnabled = value;
  80572. this._updateParameters();
  80573. },
  80574. enumerable: true,
  80575. configurable: true
  80576. });
  80577. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  80578. /**
  80579. * Gets wether the color grading effect is enabled.
  80580. */
  80581. get: function () {
  80582. return this._colorGradingEnabled;
  80583. },
  80584. /**
  80585. * Sets wether the color grading effect is enabled.
  80586. */
  80587. set: function (value) {
  80588. if (this._colorGradingEnabled === value) {
  80589. return;
  80590. }
  80591. this._colorGradingEnabled = value;
  80592. this._updateParameters();
  80593. },
  80594. enumerable: true,
  80595. configurable: true
  80596. });
  80597. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  80598. /**
  80599. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  80600. */
  80601. get: function () {
  80602. return this._colorGradingWithGreenDepth;
  80603. },
  80604. /**
  80605. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  80606. */
  80607. set: function (value) {
  80608. if (this._colorGradingWithGreenDepth === value) {
  80609. return;
  80610. }
  80611. this._colorGradingWithGreenDepth = value;
  80612. this._updateParameters();
  80613. },
  80614. enumerable: true,
  80615. configurable: true
  80616. });
  80617. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  80618. /**
  80619. * Gets wether the color grading texture contains BGR values.
  80620. */
  80621. get: function () {
  80622. return this._colorGradingBGR;
  80623. },
  80624. /**
  80625. * Sets wether the color grading texture contains BGR values.
  80626. */
  80627. set: function (value) {
  80628. if (this._colorGradingBGR === value) {
  80629. return;
  80630. }
  80631. this._colorGradingBGR = value;
  80632. this._updateParameters();
  80633. },
  80634. enumerable: true,
  80635. configurable: true
  80636. });
  80637. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  80638. /**
  80639. * Gets the Exposure used in the effect.
  80640. */
  80641. get: function () {
  80642. return this._exposure;
  80643. },
  80644. /**
  80645. * Sets the Exposure used in the effect.
  80646. */
  80647. set: function (value) {
  80648. if (this._exposure === value) {
  80649. return;
  80650. }
  80651. this._exposure = value;
  80652. this._updateParameters();
  80653. },
  80654. enumerable: true,
  80655. configurable: true
  80656. });
  80657. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  80658. /**
  80659. * Gets wether the tone mapping effect is enabled.
  80660. */
  80661. get: function () {
  80662. return this._toneMappingEnabled;
  80663. },
  80664. /**
  80665. * Sets wether the tone mapping effect is enabled.
  80666. */
  80667. set: function (value) {
  80668. if (this._toneMappingEnabled === value) {
  80669. return;
  80670. }
  80671. this._toneMappingEnabled = value;
  80672. this._updateParameters();
  80673. },
  80674. enumerable: true,
  80675. configurable: true
  80676. });
  80677. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  80678. /**
  80679. * Gets the type of tone mapping effect.
  80680. */
  80681. get: function () {
  80682. return this._toneMappingType;
  80683. },
  80684. /**
  80685. * Sets the type of tone mapping effect used in BabylonJS.
  80686. */
  80687. set: function (value) {
  80688. if (this._toneMappingType === value) {
  80689. return;
  80690. }
  80691. this._toneMappingType = value;
  80692. this._updateParameters();
  80693. },
  80694. enumerable: true,
  80695. configurable: true
  80696. });
  80697. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  80698. /**
  80699. * Gets the contrast used in the effect.
  80700. */
  80701. get: function () {
  80702. return this._contrast;
  80703. },
  80704. /**
  80705. * Sets the contrast used in the effect.
  80706. */
  80707. set: function (value) {
  80708. if (this._contrast === value) {
  80709. return;
  80710. }
  80711. this._contrast = value;
  80712. this._updateParameters();
  80713. },
  80714. enumerable: true,
  80715. configurable: true
  80716. });
  80717. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  80718. /**
  80719. * Gets the vignette blend mode allowing different kind of effect.
  80720. */
  80721. get: function () {
  80722. return this._vignetteBlendMode;
  80723. },
  80724. /**
  80725. * Sets the vignette blend mode allowing different kind of effect.
  80726. */
  80727. set: function (value) {
  80728. if (this._vignetteBlendMode === value) {
  80729. return;
  80730. }
  80731. this._vignetteBlendMode = value;
  80732. this._updateParameters();
  80733. },
  80734. enumerable: true,
  80735. configurable: true
  80736. });
  80737. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  80738. /**
  80739. * Gets wether the vignette effect is enabled.
  80740. */
  80741. get: function () {
  80742. return this._vignetteEnabled;
  80743. },
  80744. /**
  80745. * Sets wether the vignette effect is enabled.
  80746. */
  80747. set: function (value) {
  80748. if (this._vignetteEnabled === value) {
  80749. return;
  80750. }
  80751. this._vignetteEnabled = value;
  80752. this._updateParameters();
  80753. },
  80754. enumerable: true,
  80755. configurable: true
  80756. });
  80757. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  80758. /**
  80759. * Gets wether the image processing is applied through a post process or not.
  80760. */
  80761. get: function () {
  80762. return this._applyByPostProcess;
  80763. },
  80764. /**
  80765. * Sets wether the image processing is applied through a post process or not.
  80766. */
  80767. set: function (value) {
  80768. if (this._applyByPostProcess === value) {
  80769. return;
  80770. }
  80771. this._applyByPostProcess = value;
  80772. this._updateParameters();
  80773. },
  80774. enumerable: true,
  80775. configurable: true
  80776. });
  80777. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  80778. /**
  80779. * Gets wether the image processing is enabled or not.
  80780. */
  80781. get: function () {
  80782. return this._isEnabled;
  80783. },
  80784. /**
  80785. * Sets wether the image processing is enabled or not.
  80786. */
  80787. set: function (value) {
  80788. if (this._isEnabled === value) {
  80789. return;
  80790. }
  80791. this._isEnabled = value;
  80792. this._updateParameters();
  80793. },
  80794. enumerable: true,
  80795. configurable: true
  80796. });
  80797. /**
  80798. * Method called each time the image processing information changes requires to recompile the effect.
  80799. */
  80800. ImageProcessingConfiguration.prototype._updateParameters = function () {
  80801. this.onUpdateParameters.notifyObservers(this);
  80802. };
  80803. ImageProcessingConfiguration.prototype.getClassName = function () {
  80804. return "ImageProcessingConfiguration";
  80805. };
  80806. /**
  80807. * Prepare the list of uniforms associated with the Image Processing effects.
  80808. * @param uniformsList The list of uniforms used in the effect
  80809. * @param defines the list of defines currently in use
  80810. */
  80811. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  80812. if (defines.EXPOSURE) {
  80813. uniforms.push("exposureLinear");
  80814. }
  80815. if (defines.CONTRAST) {
  80816. uniforms.push("contrast");
  80817. }
  80818. if (defines.COLORGRADING) {
  80819. uniforms.push("colorTransformSettings");
  80820. }
  80821. if (defines.VIGNETTE) {
  80822. uniforms.push("vInverseScreenSize");
  80823. uniforms.push("vignetteSettings1");
  80824. uniforms.push("vignetteSettings2");
  80825. }
  80826. if (defines.COLORCURVES) {
  80827. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  80828. }
  80829. };
  80830. /**
  80831. * Prepare the list of samplers associated with the Image Processing effects.
  80832. * @param uniformsList The list of uniforms used in the effect
  80833. * @param defines the list of defines currently in use
  80834. */
  80835. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  80836. if (defines.COLORGRADING) {
  80837. samplersList.push("txColorTransform");
  80838. }
  80839. };
  80840. /**
  80841. * Prepare the list of defines associated to the shader.
  80842. * @param defines the list of defines to complete
  80843. */
  80844. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  80845. if (forPostProcess === void 0) { forPostProcess = false; }
  80846. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  80847. defines.VIGNETTE = false;
  80848. defines.TONEMAPPING = false;
  80849. defines.TONEMAPPING_ACES = false;
  80850. defines.CONTRAST = false;
  80851. defines.EXPOSURE = false;
  80852. defines.COLORCURVES = false;
  80853. defines.COLORGRADING = false;
  80854. defines.COLORGRADING3D = false;
  80855. defines.IMAGEPROCESSING = false;
  80856. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  80857. return;
  80858. }
  80859. defines.VIGNETTE = this.vignetteEnabled;
  80860. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  80861. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  80862. defines.TONEMAPPING = this.toneMappingEnabled;
  80863. switch (this._toneMappingType) {
  80864. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  80865. defines.TONEMAPPING_ACES = true;
  80866. break;
  80867. }
  80868. defines.CONTRAST = (this.contrast !== 1.0);
  80869. defines.EXPOSURE = (this.exposure !== 1.0);
  80870. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  80871. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  80872. if (defines.COLORGRADING) {
  80873. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  80874. }
  80875. else {
  80876. defines.COLORGRADING3D = false;
  80877. }
  80878. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  80879. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  80880. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  80881. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  80882. };
  80883. /**
  80884. * Returns true if all the image processing information are ready.
  80885. */
  80886. ImageProcessingConfiguration.prototype.isReady = function () {
  80887. // Color Grading texure can not be none blocking.
  80888. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  80889. };
  80890. /**
  80891. * Binds the image processing to the shader.
  80892. * @param effect The effect to bind to
  80893. */
  80894. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  80895. if (aspectRatio === void 0) { aspectRatio = 1; }
  80896. // Color Curves
  80897. if (this._colorCurvesEnabled && this.colorCurves) {
  80898. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  80899. }
  80900. // Vignette
  80901. if (this._vignetteEnabled) {
  80902. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  80903. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  80904. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  80905. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  80906. var vignetteScaleX = vignetteScaleY * aspectRatio;
  80907. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  80908. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  80909. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  80910. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  80911. var vignettePower = -2.0 * this.vignetteWeight;
  80912. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  80913. }
  80914. // Exposure
  80915. effect.setFloat("exposureLinear", this.exposure);
  80916. // Contrast
  80917. effect.setFloat("contrast", this.contrast);
  80918. // Color transform settings
  80919. if (this.colorGradingTexture) {
  80920. effect.setTexture("txColorTransform", this.colorGradingTexture);
  80921. var textureSize = this.colorGradingTexture.getSize().height;
  80922. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  80923. 0.5 / textureSize, // textureOffset
  80924. textureSize, // textureSize
  80925. this.colorGradingTexture.level // weight
  80926. );
  80927. }
  80928. };
  80929. /**
  80930. * Clones the current image processing instance.
  80931. * @return The cloned image processing
  80932. */
  80933. ImageProcessingConfiguration.prototype.clone = function () {
  80934. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  80935. };
  80936. /**
  80937. * Serializes the current image processing instance to a json representation.
  80938. * @return a JSON representation
  80939. */
  80940. ImageProcessingConfiguration.prototype.serialize = function () {
  80941. return BABYLON.SerializationHelper.Serialize(this);
  80942. };
  80943. /**
  80944. * Parses the image processing from a json representation.
  80945. * @param source the JSON source to parse
  80946. * @return The parsed image processing
  80947. */
  80948. ImageProcessingConfiguration.Parse = function (source) {
  80949. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  80950. };
  80951. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  80952. /**
  80953. * Used to apply the vignette as a mix with the pixel color.
  80954. */
  80955. get: function () {
  80956. return this._VIGNETTEMODE_MULTIPLY;
  80957. },
  80958. enumerable: true,
  80959. configurable: true
  80960. });
  80961. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  80962. /**
  80963. * Used to apply the vignette as a replacement of the pixel color.
  80964. */
  80965. get: function () {
  80966. return this._VIGNETTEMODE_OPAQUE;
  80967. },
  80968. enumerable: true,
  80969. configurable: true
  80970. });
  80971. /**
  80972. * Default tone mapping applied in BabylonJS.
  80973. */
  80974. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  80975. /**
  80976. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  80977. * to other engines rendering to increase portability.
  80978. */
  80979. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  80980. // Static constants associated to the image processing.
  80981. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  80982. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  80983. __decorate([
  80984. BABYLON.serializeAsColorCurves()
  80985. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  80986. __decorate([
  80987. BABYLON.serialize()
  80988. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  80989. __decorate([
  80990. BABYLON.serializeAsTexture()
  80991. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  80992. __decorate([
  80993. BABYLON.serialize()
  80994. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  80995. __decorate([
  80996. BABYLON.serialize()
  80997. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  80998. __decorate([
  80999. BABYLON.serialize()
  81000. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  81001. __decorate([
  81002. BABYLON.serialize()
  81003. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  81004. __decorate([
  81005. BABYLON.serialize()
  81006. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  81007. __decorate([
  81008. BABYLON.serialize()
  81009. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  81010. __decorate([
  81011. BABYLON.serialize()
  81012. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  81013. __decorate([
  81014. BABYLON.serialize()
  81015. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  81016. __decorate([
  81017. BABYLON.serialize()
  81018. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  81019. __decorate([
  81020. BABYLON.serialize()
  81021. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  81022. __decorate([
  81023. BABYLON.serialize()
  81024. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  81025. __decorate([
  81026. BABYLON.serializeAsColor4()
  81027. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  81028. __decorate([
  81029. BABYLON.serialize()
  81030. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  81031. __decorate([
  81032. BABYLON.serialize()
  81033. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  81034. __decorate([
  81035. BABYLON.serialize()
  81036. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  81037. __decorate([
  81038. BABYLON.serialize()
  81039. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  81040. __decorate([
  81041. BABYLON.serialize()
  81042. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  81043. return ImageProcessingConfiguration;
  81044. }());
  81045. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  81046. })(BABYLON || (BABYLON = {}));
  81047. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  81048. var BABYLON;
  81049. (function (BABYLON) {
  81050. /**
  81051. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  81052. * It can help converting any input color in a desired output one. This can then be used to create effects
  81053. * from sepia, black and white to sixties or futuristic rendering...
  81054. *
  81055. * The only supported format is currently 3dl.
  81056. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  81057. */
  81058. var ColorGradingTexture = /** @class */ (function (_super) {
  81059. __extends(ColorGradingTexture, _super);
  81060. /**
  81061. * Instantiates a ColorGradingTexture from the following parameters.
  81062. *
  81063. * @param url The location of the color gradind data (currently only supporting 3dl)
  81064. * @param scene The scene the texture will be used in
  81065. */
  81066. function ColorGradingTexture(url, scene) {
  81067. var _this = _super.call(this, scene) || this;
  81068. if (!url) {
  81069. return _this;
  81070. }
  81071. _this._engine = scene.getEngine();
  81072. _this._textureMatrix = BABYLON.Matrix.Identity();
  81073. _this.name = url;
  81074. _this.url = url;
  81075. _this.hasAlpha = false;
  81076. _this.isCube = false;
  81077. _this.is3D = _this._engine.webGLVersion > 1;
  81078. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81079. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81080. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81081. _this.anisotropicFilteringLevel = 1;
  81082. _this._texture = _this._getFromCache(url, true);
  81083. if (!_this._texture) {
  81084. if (!scene.useDelayedTextureLoading) {
  81085. _this.loadTexture();
  81086. }
  81087. else {
  81088. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  81089. }
  81090. }
  81091. return _this;
  81092. }
  81093. /**
  81094. * Returns the texture matrix used in most of the material.
  81095. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  81096. */
  81097. ColorGradingTexture.prototype.getTextureMatrix = function () {
  81098. return this._textureMatrix;
  81099. };
  81100. /**
  81101. * Occurs when the file being loaded is a .3dl LUT file.
  81102. */
  81103. ColorGradingTexture.prototype.load3dlTexture = function () {
  81104. var engine = this._engine;
  81105. var texture;
  81106. if (engine.webGLVersion === 1) {
  81107. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  81108. }
  81109. else {
  81110. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  81111. }
  81112. this._texture = texture;
  81113. var callback = function (text) {
  81114. if (typeof text !== "string") {
  81115. return;
  81116. }
  81117. var data = null;
  81118. var tempData = null;
  81119. var line;
  81120. var lines = text.split('\n');
  81121. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  81122. var maxColor = 0;
  81123. for (var i = 0; i < lines.length; i++) {
  81124. line = lines[i];
  81125. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  81126. continue;
  81127. if (line.indexOf('#') === 0)
  81128. continue;
  81129. var words = line.split(" ");
  81130. if (size === 0) {
  81131. // Number of space + one
  81132. size = words.length;
  81133. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  81134. tempData = new Float32Array(size * size * size * 4);
  81135. continue;
  81136. }
  81137. if (size != 0) {
  81138. var r = Math.max(parseInt(words[0]), 0);
  81139. var g = Math.max(parseInt(words[1]), 0);
  81140. var b = Math.max(parseInt(words[2]), 0);
  81141. maxColor = Math.max(r, maxColor);
  81142. maxColor = Math.max(g, maxColor);
  81143. maxColor = Math.max(b, maxColor);
  81144. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  81145. if (tempData) {
  81146. tempData[pixelStorageIndex + 0] = r;
  81147. tempData[pixelStorageIndex + 1] = g;
  81148. tempData[pixelStorageIndex + 2] = b;
  81149. }
  81150. pixelIndexSlice++;
  81151. if (pixelIndexSlice % size == 0) {
  81152. pixelIndexH++;
  81153. pixelIndexSlice = 0;
  81154. if (pixelIndexH % size == 0) {
  81155. pixelIndexW++;
  81156. pixelIndexH = 0;
  81157. }
  81158. }
  81159. }
  81160. }
  81161. if (tempData && data) {
  81162. for (var i = 0; i < tempData.length; i++) {
  81163. if (i > 0 && (i + 1) % 4 === 0) {
  81164. data[i] = 255;
  81165. }
  81166. else {
  81167. var value = tempData[i];
  81168. data[i] = (value / maxColor * 255);
  81169. }
  81170. }
  81171. }
  81172. if (texture.is3D) {
  81173. texture.updateSize(size, size, size);
  81174. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  81175. }
  81176. else {
  81177. texture.updateSize(size * size, size);
  81178. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  81179. }
  81180. };
  81181. var scene = this.getScene();
  81182. if (scene) {
  81183. scene._loadFile(this.url, callback);
  81184. }
  81185. else {
  81186. this._engine._loadFile(this.url, callback);
  81187. }
  81188. return this._texture;
  81189. };
  81190. /**
  81191. * Starts the loading process of the texture.
  81192. */
  81193. ColorGradingTexture.prototype.loadTexture = function () {
  81194. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  81195. this.load3dlTexture();
  81196. }
  81197. };
  81198. /**
  81199. * Clones the color gradind texture.
  81200. */
  81201. ColorGradingTexture.prototype.clone = function () {
  81202. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  81203. // Base texture
  81204. newTexture.level = this.level;
  81205. return newTexture;
  81206. };
  81207. /**
  81208. * Called during delayed load for textures.
  81209. */
  81210. ColorGradingTexture.prototype.delayLoad = function () {
  81211. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  81212. return;
  81213. }
  81214. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  81215. this._texture = this._getFromCache(this.url, true);
  81216. if (!this._texture) {
  81217. this.loadTexture();
  81218. }
  81219. };
  81220. /**
  81221. * Parses a color grading texture serialized by Babylon.
  81222. * @param parsedTexture The texture information being parsedTexture
  81223. * @param scene The scene to load the texture in
  81224. * @param rootUrl The root url of the data assets to load
  81225. * @return A color gradind texture
  81226. */
  81227. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  81228. var texture = null;
  81229. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  81230. texture = new ColorGradingTexture(parsedTexture.name, scene);
  81231. texture.name = parsedTexture.name;
  81232. texture.level = parsedTexture.level;
  81233. }
  81234. return texture;
  81235. };
  81236. /**
  81237. * Serializes the LUT texture to json format.
  81238. */
  81239. ColorGradingTexture.prototype.serialize = function () {
  81240. if (!this.name) {
  81241. return null;
  81242. }
  81243. var serializationObject = {};
  81244. serializationObject.name = this.name;
  81245. serializationObject.level = this.level;
  81246. serializationObject.customType = "BABYLON.ColorGradingTexture";
  81247. return serializationObject;
  81248. };
  81249. /**
  81250. * Empty line regex stored for GC.
  81251. */
  81252. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  81253. return ColorGradingTexture;
  81254. }(BABYLON.BaseTexture));
  81255. BABYLON.ColorGradingTexture = ColorGradingTexture;
  81256. })(BABYLON || (BABYLON = {}));
  81257. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  81258. var BABYLON;
  81259. (function (BABYLON) {
  81260. /**
  81261. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  81262. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  81263. * 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;
  81264. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  81265. */
  81266. var ColorCurves = /** @class */ (function () {
  81267. function ColorCurves() {
  81268. this._dirty = true;
  81269. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  81270. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  81271. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  81272. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  81273. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  81274. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  81275. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  81276. this._globalHue = 30;
  81277. this._globalDensity = 0;
  81278. this._globalSaturation = 0;
  81279. this._globalExposure = 0;
  81280. this._highlightsHue = 30;
  81281. this._highlightsDensity = 0;
  81282. this._highlightsSaturation = 0;
  81283. this._highlightsExposure = 0;
  81284. this._midtonesHue = 30;
  81285. this._midtonesDensity = 0;
  81286. this._midtonesSaturation = 0;
  81287. this._midtonesExposure = 0;
  81288. this._shadowsHue = 30;
  81289. this._shadowsDensity = 0;
  81290. this._shadowsSaturation = 0;
  81291. this._shadowsExposure = 0;
  81292. }
  81293. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  81294. /**
  81295. * Gets the global Hue value.
  81296. * 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).
  81297. */
  81298. get: function () {
  81299. return this._globalHue;
  81300. },
  81301. /**
  81302. * Sets the global Hue value.
  81303. * 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).
  81304. */
  81305. set: function (value) {
  81306. this._globalHue = value;
  81307. this._dirty = true;
  81308. },
  81309. enumerable: true,
  81310. configurable: true
  81311. });
  81312. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  81313. /**
  81314. * Gets the global Density value.
  81315. * 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.
  81316. * Values less than zero provide a filter of opposite hue.
  81317. */
  81318. get: function () {
  81319. return this._globalDensity;
  81320. },
  81321. /**
  81322. * Sets the global Density value.
  81323. * 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.
  81324. * Values less than zero provide a filter of opposite hue.
  81325. */
  81326. set: function (value) {
  81327. this._globalDensity = value;
  81328. this._dirty = true;
  81329. },
  81330. enumerable: true,
  81331. configurable: true
  81332. });
  81333. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  81334. /**
  81335. * Gets the global Saturation value.
  81336. * 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.
  81337. */
  81338. get: function () {
  81339. return this._globalSaturation;
  81340. },
  81341. /**
  81342. * Sets the global Saturation value.
  81343. * 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.
  81344. */
  81345. set: function (value) {
  81346. this._globalSaturation = value;
  81347. this._dirty = true;
  81348. },
  81349. enumerable: true,
  81350. configurable: true
  81351. });
  81352. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  81353. /**
  81354. * Gets the global Exposure value.
  81355. * 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.
  81356. */
  81357. get: function () {
  81358. return this._globalExposure;
  81359. },
  81360. /**
  81361. * Sets the global Exposure value.
  81362. * 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.
  81363. */
  81364. set: function (value) {
  81365. this._globalExposure = value;
  81366. this._dirty = true;
  81367. },
  81368. enumerable: true,
  81369. configurable: true
  81370. });
  81371. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  81372. /**
  81373. * Gets the highlights Hue value.
  81374. * 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).
  81375. */
  81376. get: function () {
  81377. return this._highlightsHue;
  81378. },
  81379. /**
  81380. * Sets the highlights Hue value.
  81381. * 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).
  81382. */
  81383. set: function (value) {
  81384. this._highlightsHue = value;
  81385. this._dirty = true;
  81386. },
  81387. enumerable: true,
  81388. configurable: true
  81389. });
  81390. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  81391. /**
  81392. * Gets the highlights Density value.
  81393. * 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.
  81394. * Values less than zero provide a filter of opposite hue.
  81395. */
  81396. get: function () {
  81397. return this._highlightsDensity;
  81398. },
  81399. /**
  81400. * Sets the highlights Density value.
  81401. * 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.
  81402. * Values less than zero provide a filter of opposite hue.
  81403. */
  81404. set: function (value) {
  81405. this._highlightsDensity = value;
  81406. this._dirty = true;
  81407. },
  81408. enumerable: true,
  81409. configurable: true
  81410. });
  81411. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  81412. /**
  81413. * Gets the highlights Saturation value.
  81414. * 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.
  81415. */
  81416. get: function () {
  81417. return this._highlightsSaturation;
  81418. },
  81419. /**
  81420. * Sets the highlights Saturation value.
  81421. * 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.
  81422. */
  81423. set: function (value) {
  81424. this._highlightsSaturation = value;
  81425. this._dirty = true;
  81426. },
  81427. enumerable: true,
  81428. configurable: true
  81429. });
  81430. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  81431. /**
  81432. * Gets the highlights Exposure value.
  81433. * 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.
  81434. */
  81435. get: function () {
  81436. return this._highlightsExposure;
  81437. },
  81438. /**
  81439. * Sets the highlights Exposure value.
  81440. * 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.
  81441. */
  81442. set: function (value) {
  81443. this._highlightsExposure = value;
  81444. this._dirty = true;
  81445. },
  81446. enumerable: true,
  81447. configurable: true
  81448. });
  81449. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  81450. /**
  81451. * Gets the midtones Hue value.
  81452. * 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).
  81453. */
  81454. get: function () {
  81455. return this._midtonesHue;
  81456. },
  81457. /**
  81458. * Sets the midtones Hue value.
  81459. * 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).
  81460. */
  81461. set: function (value) {
  81462. this._midtonesHue = value;
  81463. this._dirty = true;
  81464. },
  81465. enumerable: true,
  81466. configurable: true
  81467. });
  81468. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  81469. /**
  81470. * Gets the midtones Density value.
  81471. * 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.
  81472. * Values less than zero provide a filter of opposite hue.
  81473. */
  81474. get: function () {
  81475. return this._midtonesDensity;
  81476. },
  81477. /**
  81478. * Sets the midtones Density value.
  81479. * 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.
  81480. * Values less than zero provide a filter of opposite hue.
  81481. */
  81482. set: function (value) {
  81483. this._midtonesDensity = value;
  81484. this._dirty = true;
  81485. },
  81486. enumerable: true,
  81487. configurable: true
  81488. });
  81489. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  81490. /**
  81491. * Gets the midtones Saturation value.
  81492. * 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.
  81493. */
  81494. get: function () {
  81495. return this._midtonesSaturation;
  81496. },
  81497. /**
  81498. * Sets the midtones Saturation value.
  81499. * 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.
  81500. */
  81501. set: function (value) {
  81502. this._midtonesSaturation = value;
  81503. this._dirty = true;
  81504. },
  81505. enumerable: true,
  81506. configurable: true
  81507. });
  81508. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  81509. /**
  81510. * Gets the midtones Exposure value.
  81511. * 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.
  81512. */
  81513. get: function () {
  81514. return this._midtonesExposure;
  81515. },
  81516. /**
  81517. * Sets the midtones Exposure value.
  81518. * 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.
  81519. */
  81520. set: function (value) {
  81521. this._midtonesExposure = value;
  81522. this._dirty = true;
  81523. },
  81524. enumerable: true,
  81525. configurable: true
  81526. });
  81527. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  81528. /**
  81529. * Gets the shadows Hue value.
  81530. * 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).
  81531. */
  81532. get: function () {
  81533. return this._shadowsHue;
  81534. },
  81535. /**
  81536. * Sets the shadows Hue value.
  81537. * 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).
  81538. */
  81539. set: function (value) {
  81540. this._shadowsHue = value;
  81541. this._dirty = true;
  81542. },
  81543. enumerable: true,
  81544. configurable: true
  81545. });
  81546. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  81547. /**
  81548. * Gets the shadows Density value.
  81549. * 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.
  81550. * Values less than zero provide a filter of opposite hue.
  81551. */
  81552. get: function () {
  81553. return this._shadowsDensity;
  81554. },
  81555. /**
  81556. * Sets the shadows Density value.
  81557. * 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.
  81558. * Values less than zero provide a filter of opposite hue.
  81559. */
  81560. set: function (value) {
  81561. this._shadowsDensity = value;
  81562. this._dirty = true;
  81563. },
  81564. enumerable: true,
  81565. configurable: true
  81566. });
  81567. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  81568. /**
  81569. * Gets the shadows Saturation value.
  81570. * 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.
  81571. */
  81572. get: function () {
  81573. return this._shadowsSaturation;
  81574. },
  81575. /**
  81576. * Sets the shadows Saturation value.
  81577. * 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.
  81578. */
  81579. set: function (value) {
  81580. this._shadowsSaturation = value;
  81581. this._dirty = true;
  81582. },
  81583. enumerable: true,
  81584. configurable: true
  81585. });
  81586. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  81587. /**
  81588. * Gets the shadows Exposure value.
  81589. * 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.
  81590. */
  81591. get: function () {
  81592. return this._shadowsExposure;
  81593. },
  81594. /**
  81595. * Sets the shadows Exposure value.
  81596. * 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.
  81597. */
  81598. set: function (value) {
  81599. this._shadowsExposure = value;
  81600. this._dirty = true;
  81601. },
  81602. enumerable: true,
  81603. configurable: true
  81604. });
  81605. ColorCurves.prototype.getClassName = function () {
  81606. return "ColorCurves";
  81607. };
  81608. /**
  81609. * Binds the color curves to the shader.
  81610. * @param colorCurves The color curve to bind
  81611. * @param effect The effect to bind to
  81612. */
  81613. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  81614. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  81615. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  81616. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  81617. if (colorCurves._dirty) {
  81618. colorCurves._dirty = false;
  81619. // Fill in global info.
  81620. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  81621. // Compute highlights info.
  81622. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  81623. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  81624. // Compute midtones info.
  81625. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  81626. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  81627. // Compute shadows info.
  81628. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  81629. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  81630. // Compute deltas (neutral is midtones).
  81631. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  81632. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  81633. }
  81634. if (effect) {
  81635. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  81636. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  81637. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  81638. }
  81639. };
  81640. /**
  81641. * Prepare the list of uniforms associated with the ColorCurves effects.
  81642. * @param uniformsList The list of uniforms used in the effect
  81643. */
  81644. ColorCurves.PrepareUniforms = function (uniformsList) {
  81645. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  81646. };
  81647. /**
  81648. * Returns color grading data based on a hue, density, saturation and exposure value.
  81649. * @param filterHue The hue of the color filter.
  81650. * @param filterDensity The density of the color filter.
  81651. * @param saturation The saturation.
  81652. * @param exposure The exposure.
  81653. * @param result The result data container.
  81654. */
  81655. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  81656. if (hue == null) {
  81657. return;
  81658. }
  81659. hue = ColorCurves.clamp(hue, 0, 360);
  81660. density = ColorCurves.clamp(density, -100, 100);
  81661. saturation = ColorCurves.clamp(saturation, -100, 100);
  81662. exposure = ColorCurves.clamp(exposure, -100, 100);
  81663. // Remap the slider/config filter density with non-linear mapping and also scale by half
  81664. // so that the maximum filter density is only 50% control. This provides fine control
  81665. // for small values and reasonable range.
  81666. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  81667. density *= 0.5;
  81668. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  81669. if (density < 0) {
  81670. density *= -1;
  81671. hue = (hue + 180) % 360;
  81672. }
  81673. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  81674. result.scaleToRef(2, result);
  81675. result.a = 1 + 0.01 * saturation;
  81676. };
  81677. /**
  81678. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  81679. * @param value The input slider value in range [-100,100].
  81680. * @returns Adjusted value.
  81681. */
  81682. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  81683. value /= 100;
  81684. var x = Math.abs(value);
  81685. x = Math.pow(x, 2);
  81686. if (value < 0) {
  81687. x *= -1;
  81688. }
  81689. x *= 100;
  81690. return x;
  81691. };
  81692. /**
  81693. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  81694. * @param hue The hue (H) input.
  81695. * @param saturation The saturation (S) input.
  81696. * @param brightness The brightness (B) input.
  81697. * @result An RGBA color represented as Vector4.
  81698. */
  81699. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  81700. var h = ColorCurves.clamp(hue, 0, 360);
  81701. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  81702. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  81703. if (s === 0) {
  81704. result.r = v;
  81705. result.g = v;
  81706. result.b = v;
  81707. }
  81708. else {
  81709. // sector 0 to 5
  81710. h /= 60;
  81711. var i = Math.floor(h);
  81712. // fractional part of h
  81713. var f = h - i;
  81714. var p = v * (1 - s);
  81715. var q = v * (1 - s * f);
  81716. var t = v * (1 - s * (1 - f));
  81717. switch (i) {
  81718. case 0:
  81719. result.r = v;
  81720. result.g = t;
  81721. result.b = p;
  81722. break;
  81723. case 1:
  81724. result.r = q;
  81725. result.g = v;
  81726. result.b = p;
  81727. break;
  81728. case 2:
  81729. result.r = p;
  81730. result.g = v;
  81731. result.b = t;
  81732. break;
  81733. case 3:
  81734. result.r = p;
  81735. result.g = q;
  81736. result.b = v;
  81737. break;
  81738. case 4:
  81739. result.r = t;
  81740. result.g = p;
  81741. result.b = v;
  81742. break;
  81743. default: // case 5:
  81744. result.r = v;
  81745. result.g = p;
  81746. result.b = q;
  81747. break;
  81748. }
  81749. }
  81750. result.a = 1;
  81751. };
  81752. /**
  81753. * Returns a value clamped between min and max
  81754. * @param value The value to clamp
  81755. * @param min The minimum of value
  81756. * @param max The maximum of value
  81757. * @returns The clamped value.
  81758. */
  81759. ColorCurves.clamp = function (value, min, max) {
  81760. return Math.min(Math.max(value, min), max);
  81761. };
  81762. /**
  81763. * Clones the current color curve instance.
  81764. * @return The cloned curves
  81765. */
  81766. ColorCurves.prototype.clone = function () {
  81767. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  81768. };
  81769. /**
  81770. * Serializes the current color curve instance to a json representation.
  81771. * @return a JSON representation
  81772. */
  81773. ColorCurves.prototype.serialize = function () {
  81774. return BABYLON.SerializationHelper.Serialize(this);
  81775. };
  81776. /**
  81777. * Parses the color curve from a json representation.
  81778. * @param source the JSON source to parse
  81779. * @return The parsed curves
  81780. */
  81781. ColorCurves.Parse = function (source) {
  81782. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  81783. };
  81784. __decorate([
  81785. BABYLON.serialize()
  81786. ], ColorCurves.prototype, "_globalHue", void 0);
  81787. __decorate([
  81788. BABYLON.serialize()
  81789. ], ColorCurves.prototype, "_globalDensity", void 0);
  81790. __decorate([
  81791. BABYLON.serialize()
  81792. ], ColorCurves.prototype, "_globalSaturation", void 0);
  81793. __decorate([
  81794. BABYLON.serialize()
  81795. ], ColorCurves.prototype, "_globalExposure", void 0);
  81796. __decorate([
  81797. BABYLON.serialize()
  81798. ], ColorCurves.prototype, "_highlightsHue", void 0);
  81799. __decorate([
  81800. BABYLON.serialize()
  81801. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  81802. __decorate([
  81803. BABYLON.serialize()
  81804. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  81805. __decorate([
  81806. BABYLON.serialize()
  81807. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  81808. __decorate([
  81809. BABYLON.serialize()
  81810. ], ColorCurves.prototype, "_midtonesHue", void 0);
  81811. __decorate([
  81812. BABYLON.serialize()
  81813. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  81814. __decorate([
  81815. BABYLON.serialize()
  81816. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  81817. __decorate([
  81818. BABYLON.serialize()
  81819. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  81820. return ColorCurves;
  81821. }());
  81822. BABYLON.ColorCurves = ColorCurves;
  81823. })(BABYLON || (BABYLON = {}));
  81824. //# sourceMappingURL=babylon.colorCurves.js.map
  81825. var BABYLON;
  81826. (function (BABYLON) {
  81827. var RefractionPostProcess = /** @class */ (function (_super) {
  81828. __extends(RefractionPostProcess, _super);
  81829. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  81830. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  81831. _this.color = color;
  81832. _this.depth = depth;
  81833. _this.colorLevel = colorLevel;
  81834. _this._ownRefractionTexture = true;
  81835. _this.onActivateObservable.add(function (cam) {
  81836. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  81837. });
  81838. _this.onApplyObservable.add(function (effect) {
  81839. effect.setColor3("baseColor", _this.color);
  81840. effect.setFloat("depth", _this.depth);
  81841. effect.setFloat("colorLevel", _this.colorLevel);
  81842. effect.setTexture("refractionSampler", _this._refTexture);
  81843. });
  81844. return _this;
  81845. }
  81846. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  81847. /**
  81848. * Gets or sets the refraction texture
  81849. * Please note that you are responsible for disposing the texture if you set it manually
  81850. */
  81851. get: function () {
  81852. return this._refTexture;
  81853. },
  81854. set: function (value) {
  81855. if (this._refTexture && this._ownRefractionTexture) {
  81856. this._refTexture.dispose();
  81857. }
  81858. this._refTexture = value;
  81859. this._ownRefractionTexture = false;
  81860. },
  81861. enumerable: true,
  81862. configurable: true
  81863. });
  81864. // Methods
  81865. RefractionPostProcess.prototype.dispose = function (camera) {
  81866. if (this._refTexture && this._ownRefractionTexture) {
  81867. this._refTexture.dispose();
  81868. this._refTexture = null;
  81869. }
  81870. _super.prototype.dispose.call(this, camera);
  81871. };
  81872. return RefractionPostProcess;
  81873. }(BABYLON.PostProcess));
  81874. BABYLON.RefractionPostProcess = RefractionPostProcess;
  81875. })(BABYLON || (BABYLON = {}));
  81876. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  81877. var BABYLON;
  81878. (function (BABYLON) {
  81879. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  81880. __extends(BlackAndWhitePostProcess, _super);
  81881. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  81882. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  81883. _this.degree = 1;
  81884. _this.onApplyObservable.add(function (effect) {
  81885. effect.setFloat("degree", _this.degree);
  81886. });
  81887. return _this;
  81888. }
  81889. return BlackAndWhitePostProcess;
  81890. }(BABYLON.PostProcess));
  81891. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  81892. })(BABYLON || (BABYLON = {}));
  81893. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  81894. var BABYLON;
  81895. (function (BABYLON) {
  81896. /**
  81897. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  81898. * input texture to perform effects such as edge detection or sharpening
  81899. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  81900. */
  81901. var ConvolutionPostProcess = /** @class */ (function (_super) {
  81902. __extends(ConvolutionPostProcess, _super);
  81903. /**
  81904. * Creates a new instance ConvolutionPostProcess
  81905. * @param name The name of the effect.
  81906. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  81907. * @param options The required width/height ratio to downsize to before computing the render pass.
  81908. * @param camera The camera to apply the render pass to.
  81909. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  81910. * @param engine The engine which the post process will be applied. (default: current engine)
  81911. * @param reusable If the post process can be reused on the same frame. (default: false)
  81912. * @param textureType Type of textures used when performing the post process. (default: 0)
  81913. */
  81914. function ConvolutionPostProcess(name,
  81915. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  81916. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  81917. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81918. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  81919. _this.kernel = kernel;
  81920. _this.onApply = function (effect) {
  81921. effect.setFloat2("screenSize", _this.width, _this.height);
  81922. effect.setArray("kernel", _this.kernel);
  81923. };
  81924. return _this;
  81925. }
  81926. // Statics
  81927. /**
  81928. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81929. */
  81930. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  81931. /**
  81932. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81933. */
  81934. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  81935. /**
  81936. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81937. */
  81938. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  81939. /**
  81940. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81941. */
  81942. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  81943. /**
  81944. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81945. */
  81946. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  81947. /**
  81948. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81949. */
  81950. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  81951. return ConvolutionPostProcess;
  81952. }(BABYLON.PostProcess));
  81953. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  81954. })(BABYLON || (BABYLON = {}));
  81955. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  81956. var BABYLON;
  81957. (function (BABYLON) {
  81958. var FilterPostProcess = /** @class */ (function (_super) {
  81959. __extends(FilterPostProcess, _super);
  81960. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  81961. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  81962. _this.kernelMatrix = kernelMatrix;
  81963. _this.onApply = function (effect) {
  81964. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  81965. };
  81966. return _this;
  81967. }
  81968. return FilterPostProcess;
  81969. }(BABYLON.PostProcess));
  81970. BABYLON.FilterPostProcess = FilterPostProcess;
  81971. })(BABYLON || (BABYLON = {}));
  81972. //# sourceMappingURL=babylon.filterPostProcess.js.map
  81973. var BABYLON;
  81974. (function (BABYLON) {
  81975. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  81976. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  81977. __extends(VolumetricLightScatteringPostProcess, _super);
  81978. /**
  81979. * @constructor
  81980. * @param {string} name - The post-process name
  81981. * @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)
  81982. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  81983. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  81984. * @param {number} samples - The post-process quality, default 100
  81985. * @param {number} samplingMode - The post-process filtering mode
  81986. * @param {BABYLON.Engine} engine - The babylon engine
  81987. * @param {boolean} reusable - If the post-process is reusable
  81988. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  81989. */
  81990. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  81991. if (samples === void 0) { samples = 100; }
  81992. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  81993. 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;
  81994. _this._screenCoordinates = BABYLON.Vector2.Zero();
  81995. /**
  81996. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  81997. */
  81998. _this.customMeshPosition = BABYLON.Vector3.Zero();
  81999. /**
  82000. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  82001. */
  82002. _this.useCustomMeshPosition = false;
  82003. /**
  82004. * If the post-process should inverse the light scattering direction
  82005. */
  82006. _this.invert = true;
  82007. /**
  82008. * Array containing the excluded meshes not rendered in the internal pass
  82009. */
  82010. _this.excludedMeshes = new Array();
  82011. /**
  82012. * Controls the overall intensity of the post-process
  82013. */
  82014. _this.exposure = 0.3;
  82015. /**
  82016. * Dissipates each sample's contribution in range [0, 1]
  82017. */
  82018. _this.decay = 0.96815;
  82019. /**
  82020. * Controls the overall intensity of each sample
  82021. */
  82022. _this.weight = 0.58767;
  82023. /**
  82024. * Controls the density of each sample
  82025. */
  82026. _this.density = 0.926;
  82027. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  82028. engine = scene.getEngine();
  82029. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  82030. // Configure mesh
  82031. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  82032. // Configure
  82033. _this._createPass(scene, ratio.passRatio || ratio);
  82034. _this.onActivate = function (camera) {
  82035. if (!_this.isSupported) {
  82036. _this.dispose(camera);
  82037. }
  82038. _this.onActivate = null;
  82039. };
  82040. _this.onApplyObservable.add(function (effect) {
  82041. _this._updateMeshScreenCoordinates(scene);
  82042. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  82043. effect.setFloat("exposure", _this.exposure);
  82044. effect.setFloat("decay", _this.decay);
  82045. effect.setFloat("weight", _this.weight);
  82046. effect.setFloat("density", _this.density);
  82047. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  82048. });
  82049. return _this;
  82050. }
  82051. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  82052. get: function () {
  82053. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  82054. return false;
  82055. },
  82056. set: function (useDiffuseColor) {
  82057. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  82058. },
  82059. enumerable: true,
  82060. configurable: true
  82061. });
  82062. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  82063. return "VolumetricLightScatteringPostProcess";
  82064. };
  82065. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  82066. var mesh = subMesh.getMesh();
  82067. // Render this.mesh as default
  82068. if (mesh === this.mesh && mesh.material) {
  82069. return mesh.material.isReady(mesh);
  82070. }
  82071. var defines = [];
  82072. var attribs = [BABYLON.VertexBuffer.PositionKind];
  82073. var material = subMesh.getMaterial();
  82074. // Alpha test
  82075. if (material) {
  82076. if (material.needAlphaTesting()) {
  82077. defines.push("#define ALPHATEST");
  82078. }
  82079. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82080. attribs.push(BABYLON.VertexBuffer.UVKind);
  82081. defines.push("#define UV1");
  82082. }
  82083. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  82084. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82085. defines.push("#define UV2");
  82086. }
  82087. }
  82088. // Bones
  82089. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82090. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82091. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82092. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82093. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  82094. }
  82095. else {
  82096. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82097. }
  82098. // Instances
  82099. if (useInstances) {
  82100. defines.push("#define INSTANCES");
  82101. attribs.push("world0");
  82102. attribs.push("world1");
  82103. attribs.push("world2");
  82104. attribs.push("world3");
  82105. }
  82106. // Get correct effect
  82107. var join = defines.join("\n");
  82108. if (this._cachedDefines !== join) {
  82109. this._cachedDefines = join;
  82110. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  82111. }
  82112. return this._volumetricLightScatteringPass.isReady();
  82113. };
  82114. /**
  82115. * Sets the new light position for light scattering effect
  82116. * @param {BABYLON.Vector3} The new custom light position
  82117. */
  82118. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  82119. this.customMeshPosition = position;
  82120. };
  82121. /**
  82122. * Returns the light position for light scattering effect
  82123. * @return {BABYLON.Vector3} The custom light position
  82124. */
  82125. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  82126. return this.customMeshPosition;
  82127. };
  82128. /**
  82129. * Disposes the internal assets and detaches the post-process from the camera
  82130. */
  82131. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  82132. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  82133. if (rttIndex !== -1) {
  82134. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  82135. }
  82136. this._volumetricLightScatteringRTT.dispose();
  82137. _super.prototype.dispose.call(this, camera);
  82138. };
  82139. /**
  82140. * Returns the render target texture used by the post-process
  82141. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  82142. */
  82143. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  82144. return this._volumetricLightScatteringRTT;
  82145. };
  82146. // Private methods
  82147. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  82148. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  82149. return true;
  82150. }
  82151. return false;
  82152. };
  82153. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  82154. var _this = this;
  82155. var engine = scene.getEngine();
  82156. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82157. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82158. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82159. this._volumetricLightScatteringRTT.renderList = null;
  82160. this._volumetricLightScatteringRTT.renderParticles = false;
  82161. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  82162. var camera = this.getCamera();
  82163. if (camera) {
  82164. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  82165. }
  82166. else {
  82167. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  82168. }
  82169. // Custom render function for submeshes
  82170. var renderSubMesh = function (subMesh) {
  82171. var mesh = subMesh.getRenderingMesh();
  82172. if (_this._meshExcluded(mesh)) {
  82173. return;
  82174. }
  82175. var material = subMesh.getMaterial();
  82176. if (!material) {
  82177. return;
  82178. }
  82179. var scene = mesh.getScene();
  82180. var engine = scene.getEngine();
  82181. // Culling
  82182. engine.setState(material.backFaceCulling);
  82183. // Managing instances
  82184. var batch = mesh._getInstancesRenderList(subMesh._id);
  82185. if (batch.mustReturn) {
  82186. return;
  82187. }
  82188. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  82189. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  82190. var effect = _this._volumetricLightScatteringPass;
  82191. if (mesh === _this.mesh) {
  82192. if (subMesh.effect) {
  82193. effect = subMesh.effect;
  82194. }
  82195. else {
  82196. effect = material.getEffect();
  82197. }
  82198. }
  82199. engine.enableEffect(effect);
  82200. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  82201. if (mesh === _this.mesh) {
  82202. material.bind(mesh.getWorldMatrix(), mesh);
  82203. }
  82204. else {
  82205. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  82206. // Alpha test
  82207. if (material && material.needAlphaTesting()) {
  82208. var alphaTexture = material.getAlphaTestTexture();
  82209. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  82210. if (alphaTexture) {
  82211. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  82212. }
  82213. }
  82214. // Bones
  82215. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82216. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82217. }
  82218. }
  82219. // Draw
  82220. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  82221. }
  82222. };
  82223. // Render target texture callbacks
  82224. var savedSceneClearColor;
  82225. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  82226. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  82227. savedSceneClearColor = scene.clearColor;
  82228. scene.clearColor = sceneClearColor;
  82229. });
  82230. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  82231. scene.clearColor = savedSceneClearColor;
  82232. });
  82233. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  82234. var engine = scene.getEngine();
  82235. var index;
  82236. if (depthOnlySubMeshes.length) {
  82237. engine.setColorWrite(false);
  82238. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  82239. renderSubMesh(depthOnlySubMeshes.data[index]);
  82240. }
  82241. engine.setColorWrite(true);
  82242. }
  82243. for (index = 0; index < opaqueSubMeshes.length; index++) {
  82244. renderSubMesh(opaqueSubMeshes.data[index]);
  82245. }
  82246. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82247. renderSubMesh(alphaTestSubMeshes.data[index]);
  82248. }
  82249. if (transparentSubMeshes.length) {
  82250. // Sort sub meshes
  82251. for (index = 0; index < transparentSubMeshes.length; index++) {
  82252. var submesh = transparentSubMeshes.data[index];
  82253. var boundingInfo = submesh.getBoundingInfo();
  82254. if (boundingInfo && scene.activeCamera) {
  82255. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  82256. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  82257. }
  82258. }
  82259. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  82260. sortedArray.sort(function (a, b) {
  82261. // Alpha index first
  82262. if (a._alphaIndex > b._alphaIndex) {
  82263. return 1;
  82264. }
  82265. if (a._alphaIndex < b._alphaIndex) {
  82266. return -1;
  82267. }
  82268. // Then distance to camera
  82269. if (a._distanceToCamera < b._distanceToCamera) {
  82270. return 1;
  82271. }
  82272. if (a._distanceToCamera > b._distanceToCamera) {
  82273. return -1;
  82274. }
  82275. return 0;
  82276. });
  82277. // Render sub meshes
  82278. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  82279. for (index = 0; index < sortedArray.length; index++) {
  82280. renderSubMesh(sortedArray[index]);
  82281. }
  82282. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82283. }
  82284. };
  82285. };
  82286. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  82287. var transform = scene.getTransformMatrix();
  82288. var meshPosition;
  82289. if (this.useCustomMeshPosition) {
  82290. meshPosition = this.customMeshPosition;
  82291. }
  82292. else if (this.attachedNode) {
  82293. meshPosition = this.attachedNode.position;
  82294. }
  82295. else {
  82296. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  82297. }
  82298. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  82299. this._screenCoordinates.x = pos.x / this._viewPort.width;
  82300. this._screenCoordinates.y = pos.y / this._viewPort.height;
  82301. if (this.invert)
  82302. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  82303. };
  82304. // Static methods
  82305. /**
  82306. * Creates a default mesh for the Volumeric Light Scattering post-process
  82307. * @param {string} The mesh name
  82308. * @param {BABYLON.Scene} The scene where to create the mesh
  82309. * @return {BABYLON.Mesh} the default mesh
  82310. */
  82311. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  82312. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  82313. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  82314. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  82315. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  82316. mesh.material = material;
  82317. return mesh;
  82318. };
  82319. __decorate([
  82320. BABYLON.serializeAsVector3()
  82321. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  82322. __decorate([
  82323. BABYLON.serialize()
  82324. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  82325. __decorate([
  82326. BABYLON.serialize()
  82327. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  82328. __decorate([
  82329. BABYLON.serializeAsMeshReference()
  82330. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  82331. __decorate([
  82332. BABYLON.serialize()
  82333. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  82334. __decorate([
  82335. BABYLON.serialize()
  82336. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  82337. __decorate([
  82338. BABYLON.serialize()
  82339. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  82340. __decorate([
  82341. BABYLON.serialize()
  82342. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  82343. __decorate([
  82344. BABYLON.serialize()
  82345. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  82346. return VolumetricLightScatteringPostProcess;
  82347. }(BABYLON.PostProcess));
  82348. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  82349. })(BABYLON || (BABYLON = {}));
  82350. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  82351. //
  82352. // This post-process allows the modification of rendered colors by using
  82353. // a 'look-up table' (LUT). This effect is also called Color Grading.
  82354. //
  82355. // The object needs to be provided an url to a texture containing the color
  82356. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  82357. // Use an image editing software to tweak the LUT to match your needs.
  82358. //
  82359. // For an example of a color LUT, see here:
  82360. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  82361. // For explanations on color grading, see here:
  82362. // http://udn.epicgames.com/Three/ColorGrading.html
  82363. //
  82364. var BABYLON;
  82365. (function (BABYLON) {
  82366. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  82367. __extends(ColorCorrectionPostProcess, _super);
  82368. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  82369. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  82370. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  82371. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  82372. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82373. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82374. _this.onApply = function (effect) {
  82375. effect.setTexture("colorTable", _this._colorTableTexture);
  82376. };
  82377. return _this;
  82378. }
  82379. return ColorCorrectionPostProcess;
  82380. }(BABYLON.PostProcess));
  82381. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  82382. })(BABYLON || (BABYLON = {}));
  82383. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  82384. var BABYLON;
  82385. (function (BABYLON) {
  82386. /** Defines operator used for tonemapping */
  82387. var TonemappingOperator;
  82388. (function (TonemappingOperator) {
  82389. /** Hable */
  82390. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  82391. /** Reinhard */
  82392. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  82393. /** HejiDawson */
  82394. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  82395. /** Photographic */
  82396. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  82397. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  82398. ;
  82399. /**
  82400. * Defines a post process to apply tone mapping
  82401. */
  82402. var TonemapPostProcess = /** @class */ (function (_super) {
  82403. __extends(TonemapPostProcess, _super);
  82404. /**
  82405. * Creates a new TonemapPostProcess
  82406. * @param name defines the name of the postprocess
  82407. * @param _operator defines the operator to use
  82408. * @param exposureAdjustment defines the required exposure adjustement
  82409. * @param camera defines the camera to use (can be null)
  82410. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  82411. * @param engine defines the hosting engine (can be ignore if camera is set)
  82412. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  82413. */
  82414. function TonemapPostProcess(name, _operator,
  82415. /** Defines the required exposure adjustement */
  82416. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  82417. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82418. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82419. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  82420. _this._operator = _operator;
  82421. _this.exposureAdjustment = exposureAdjustment;
  82422. var defines = "#define ";
  82423. if (_this._operator === TonemappingOperator.Hable)
  82424. defines += "HABLE_TONEMAPPING";
  82425. else if (_this._operator === TonemappingOperator.Reinhard)
  82426. defines += "REINHARD_TONEMAPPING";
  82427. else if (_this._operator === TonemappingOperator.HejiDawson)
  82428. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  82429. else if (_this._operator === TonemappingOperator.Photographic)
  82430. defines += "PHOTOGRAPHIC_TONEMAPPING";
  82431. //sadly a second call to create the effect.
  82432. _this.updateEffect(defines);
  82433. _this.onApply = function (effect) {
  82434. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  82435. };
  82436. return _this;
  82437. }
  82438. return TonemapPostProcess;
  82439. }(BABYLON.PostProcess));
  82440. BABYLON.TonemapPostProcess = TonemapPostProcess;
  82441. })(BABYLON || (BABYLON = {}));
  82442. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  82443. var BABYLON;
  82444. (function (BABYLON) {
  82445. var DisplayPassPostProcess = /** @class */ (function (_super) {
  82446. __extends(DisplayPassPostProcess, _super);
  82447. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  82448. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  82449. }
  82450. return DisplayPassPostProcess;
  82451. }(BABYLON.PostProcess));
  82452. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  82453. })(BABYLON || (BABYLON = {}));
  82454. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  82455. var BABYLON;
  82456. (function (BABYLON) {
  82457. var HighlightsPostProcess = /** @class */ (function (_super) {
  82458. __extends(HighlightsPostProcess, _super);
  82459. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  82460. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82461. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  82462. }
  82463. return HighlightsPostProcess;
  82464. }(BABYLON.PostProcess));
  82465. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  82466. })(BABYLON || (BABYLON = {}));
  82467. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  82468. var BABYLON;
  82469. (function (BABYLON) {
  82470. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  82471. __extends(ImageProcessingPostProcess, _super);
  82472. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  82473. if (camera === void 0) { camera = null; }
  82474. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82475. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  82476. _this._fromLinearSpace = true;
  82477. /**
  82478. * Defines cache preventing GC.
  82479. */
  82480. _this._defines = {
  82481. IMAGEPROCESSING: false,
  82482. VIGNETTE: false,
  82483. VIGNETTEBLENDMODEMULTIPLY: false,
  82484. VIGNETTEBLENDMODEOPAQUE: false,
  82485. TONEMAPPING: false,
  82486. TONEMAPPING_ACES: false,
  82487. CONTRAST: false,
  82488. COLORCURVES: false,
  82489. COLORGRADING: false,
  82490. COLORGRADING3D: false,
  82491. FROMLINEARSPACE: false,
  82492. SAMPLER3DGREENDEPTH: false,
  82493. SAMPLER3DBGRMAP: false,
  82494. IMAGEPROCESSINGPOSTPROCESS: false,
  82495. EXPOSURE: false,
  82496. };
  82497. // Setup the configuration as forced by the constructor. This would then not force the
  82498. // scene materials output in linear space and let untouched the default forward pass.
  82499. if (imageProcessingConfiguration) {
  82500. imageProcessingConfiguration.applyByPostProcess = true;
  82501. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  82502. // This will cause the shader to be compiled
  82503. _this.fromLinearSpace = false;
  82504. }
  82505. // Setup the default processing configuration to the scene.
  82506. else {
  82507. _this._attachImageProcessingConfiguration(null, true);
  82508. _this.imageProcessingConfiguration.applyByPostProcess = true;
  82509. }
  82510. _this.onApply = function (effect) {
  82511. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  82512. };
  82513. return _this;
  82514. }
  82515. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  82516. /**
  82517. * Gets the image processing configuration used either in this material.
  82518. */
  82519. get: function () {
  82520. return this._imageProcessingConfiguration;
  82521. },
  82522. /**
  82523. * Sets the Default image processing configuration used either in the this material.
  82524. *
  82525. * If sets to null, the scene one is in use.
  82526. */
  82527. set: function (value) {
  82528. this._attachImageProcessingConfiguration(value);
  82529. },
  82530. enumerable: true,
  82531. configurable: true
  82532. });
  82533. /**
  82534. * Attaches a new image processing configuration to the PBR Material.
  82535. * @param configuration
  82536. */
  82537. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  82538. var _this = this;
  82539. if (doNotBuild === void 0) { doNotBuild = false; }
  82540. if (configuration === this._imageProcessingConfiguration) {
  82541. return;
  82542. }
  82543. // Detaches observer.
  82544. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  82545. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  82546. }
  82547. // Pick the scene configuration if needed.
  82548. if (!configuration) {
  82549. var scene = null;
  82550. var engine = this.getEngine();
  82551. var camera = this.getCamera();
  82552. if (camera) {
  82553. scene = camera.getScene();
  82554. }
  82555. else if (engine && engine.scenes) {
  82556. var scenes = engine.scenes;
  82557. scene = scenes[scenes.length - 1];
  82558. }
  82559. else {
  82560. scene = BABYLON.Engine.LastCreatedScene;
  82561. }
  82562. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  82563. }
  82564. else {
  82565. this._imageProcessingConfiguration = configuration;
  82566. }
  82567. // Attaches observer.
  82568. if (this._imageProcessingConfiguration) {
  82569. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  82570. _this._updateParameters();
  82571. });
  82572. }
  82573. // Ensure the effect will be rebuilt.
  82574. if (!doNotBuild) {
  82575. this._updateParameters();
  82576. }
  82577. };
  82578. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  82579. /**
  82580. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  82581. */
  82582. get: function () {
  82583. return this.imageProcessingConfiguration.colorCurves;
  82584. },
  82585. /**
  82586. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  82587. */
  82588. set: function (value) {
  82589. this.imageProcessingConfiguration.colorCurves = value;
  82590. },
  82591. enumerable: true,
  82592. configurable: true
  82593. });
  82594. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  82595. /**
  82596. * Gets wether the color curves effect is enabled.
  82597. */
  82598. get: function () {
  82599. return this.imageProcessingConfiguration.colorCurvesEnabled;
  82600. },
  82601. /**
  82602. * Sets wether the color curves effect is enabled.
  82603. */
  82604. set: function (value) {
  82605. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  82606. },
  82607. enumerable: true,
  82608. configurable: true
  82609. });
  82610. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  82611. /**
  82612. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  82613. */
  82614. get: function () {
  82615. return this.imageProcessingConfiguration.colorGradingTexture;
  82616. },
  82617. /**
  82618. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  82619. */
  82620. set: function (value) {
  82621. this.imageProcessingConfiguration.colorGradingTexture = value;
  82622. },
  82623. enumerable: true,
  82624. configurable: true
  82625. });
  82626. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  82627. /**
  82628. * Gets wether the color grading effect is enabled.
  82629. */
  82630. get: function () {
  82631. return this.imageProcessingConfiguration.colorGradingEnabled;
  82632. },
  82633. /**
  82634. * Gets wether the color grading effect is enabled.
  82635. */
  82636. set: function (value) {
  82637. this.imageProcessingConfiguration.colorGradingEnabled = value;
  82638. },
  82639. enumerable: true,
  82640. configurable: true
  82641. });
  82642. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  82643. /**
  82644. * Gets exposure used in the effect.
  82645. */
  82646. get: function () {
  82647. return this.imageProcessingConfiguration.exposure;
  82648. },
  82649. /**
  82650. * Sets exposure used in the effect.
  82651. */
  82652. set: function (value) {
  82653. this.imageProcessingConfiguration.exposure = value;
  82654. },
  82655. enumerable: true,
  82656. configurable: true
  82657. });
  82658. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  82659. /**
  82660. * Gets wether tonemapping is enabled or not.
  82661. */
  82662. get: function () {
  82663. return this._imageProcessingConfiguration.toneMappingEnabled;
  82664. },
  82665. /**
  82666. * Sets wether tonemapping is enabled or not
  82667. */
  82668. set: function (value) {
  82669. this._imageProcessingConfiguration.toneMappingEnabled = value;
  82670. },
  82671. enumerable: true,
  82672. configurable: true
  82673. });
  82674. ;
  82675. ;
  82676. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  82677. /**
  82678. * Gets contrast used in the effect.
  82679. */
  82680. get: function () {
  82681. return this.imageProcessingConfiguration.contrast;
  82682. },
  82683. /**
  82684. * Sets contrast used in the effect.
  82685. */
  82686. set: function (value) {
  82687. this.imageProcessingConfiguration.contrast = value;
  82688. },
  82689. enumerable: true,
  82690. configurable: true
  82691. });
  82692. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  82693. /**
  82694. * Gets Vignette stretch size.
  82695. */
  82696. get: function () {
  82697. return this.imageProcessingConfiguration.vignetteStretch;
  82698. },
  82699. /**
  82700. * Sets Vignette stretch size.
  82701. */
  82702. set: function (value) {
  82703. this.imageProcessingConfiguration.vignetteStretch = value;
  82704. },
  82705. enumerable: true,
  82706. configurable: true
  82707. });
  82708. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  82709. /**
  82710. * Gets Vignette centre X Offset.
  82711. */
  82712. get: function () {
  82713. return this.imageProcessingConfiguration.vignetteCentreX;
  82714. },
  82715. /**
  82716. * Sets Vignette centre X Offset.
  82717. */
  82718. set: function (value) {
  82719. this.imageProcessingConfiguration.vignetteCentreX = value;
  82720. },
  82721. enumerable: true,
  82722. configurable: true
  82723. });
  82724. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  82725. /**
  82726. * Gets Vignette centre Y Offset.
  82727. */
  82728. get: function () {
  82729. return this.imageProcessingConfiguration.vignetteCentreY;
  82730. },
  82731. /**
  82732. * Sets Vignette centre Y Offset.
  82733. */
  82734. set: function (value) {
  82735. this.imageProcessingConfiguration.vignetteCentreY = value;
  82736. },
  82737. enumerable: true,
  82738. configurable: true
  82739. });
  82740. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  82741. /**
  82742. * Gets Vignette weight or intensity of the vignette effect.
  82743. */
  82744. get: function () {
  82745. return this.imageProcessingConfiguration.vignetteWeight;
  82746. },
  82747. /**
  82748. * Sets Vignette weight or intensity of the vignette effect.
  82749. */
  82750. set: function (value) {
  82751. this.imageProcessingConfiguration.vignetteWeight = value;
  82752. },
  82753. enumerable: true,
  82754. configurable: true
  82755. });
  82756. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  82757. /**
  82758. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  82759. * if vignetteEnabled is set to true.
  82760. */
  82761. get: function () {
  82762. return this.imageProcessingConfiguration.vignetteColor;
  82763. },
  82764. /**
  82765. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  82766. * if vignetteEnabled is set to true.
  82767. */
  82768. set: function (value) {
  82769. this.imageProcessingConfiguration.vignetteColor = value;
  82770. },
  82771. enumerable: true,
  82772. configurable: true
  82773. });
  82774. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  82775. /**
  82776. * Gets Camera field of view used by the Vignette effect.
  82777. */
  82778. get: function () {
  82779. return this.imageProcessingConfiguration.vignetteCameraFov;
  82780. },
  82781. /**
  82782. * Sets Camera field of view used by the Vignette effect.
  82783. */
  82784. set: function (value) {
  82785. this.imageProcessingConfiguration.vignetteCameraFov = value;
  82786. },
  82787. enumerable: true,
  82788. configurable: true
  82789. });
  82790. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  82791. /**
  82792. * Gets the vignette blend mode allowing different kind of effect.
  82793. */
  82794. get: function () {
  82795. return this.imageProcessingConfiguration.vignetteBlendMode;
  82796. },
  82797. /**
  82798. * Sets the vignette blend mode allowing different kind of effect.
  82799. */
  82800. set: function (value) {
  82801. this.imageProcessingConfiguration.vignetteBlendMode = value;
  82802. },
  82803. enumerable: true,
  82804. configurable: true
  82805. });
  82806. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  82807. /**
  82808. * Gets wether the vignette effect is enabled.
  82809. */
  82810. get: function () {
  82811. return this.imageProcessingConfiguration.vignetteEnabled;
  82812. },
  82813. /**
  82814. * Sets wether the vignette effect is enabled.
  82815. */
  82816. set: function (value) {
  82817. this.imageProcessingConfiguration.vignetteEnabled = value;
  82818. },
  82819. enumerable: true,
  82820. configurable: true
  82821. });
  82822. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  82823. /**
  82824. * Gets wether the input of the processing is in Gamma or Linear Space.
  82825. */
  82826. get: function () {
  82827. return this._fromLinearSpace;
  82828. },
  82829. /**
  82830. * Sets wether the input of the processing is in Gamma or Linear Space.
  82831. */
  82832. set: function (value) {
  82833. if (this._fromLinearSpace === value) {
  82834. return;
  82835. }
  82836. this._fromLinearSpace = value;
  82837. this._updateParameters();
  82838. },
  82839. enumerable: true,
  82840. configurable: true
  82841. });
  82842. ImageProcessingPostProcess.prototype.getClassName = function () {
  82843. return "ImageProcessingPostProcess";
  82844. };
  82845. ImageProcessingPostProcess.prototype._updateParameters = function () {
  82846. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  82847. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  82848. var defines = "";
  82849. for (var define in this._defines) {
  82850. if (this._defines[define]) {
  82851. defines += "#define " + define + ";\r\n";
  82852. }
  82853. }
  82854. var samplers = ["textureSampler"];
  82855. var uniforms = ["scale"];
  82856. if (BABYLON.ImageProcessingConfiguration) {
  82857. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  82858. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  82859. }
  82860. this.updateEffect(defines, uniforms, samplers);
  82861. };
  82862. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  82863. _super.prototype.dispose.call(this, camera);
  82864. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  82865. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  82866. }
  82867. if (this._imageProcessingConfiguration) {
  82868. this.imageProcessingConfiguration.applyByPostProcess = false;
  82869. }
  82870. };
  82871. __decorate([
  82872. BABYLON.serialize()
  82873. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  82874. return ImageProcessingPostProcess;
  82875. }(BABYLON.PostProcess));
  82876. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  82877. })(BABYLON || (BABYLON = {}));
  82878. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  82879. var BABYLON;
  82880. (function (BABYLON) {
  82881. /**
  82882. * Class used to store bone information
  82883. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  82884. */
  82885. var Bone = /** @class */ (function (_super) {
  82886. __extends(Bone, _super);
  82887. /**
  82888. * Create a new bone
  82889. * @param name defines the bone name
  82890. * @param skeleton defines the parent skeleton
  82891. * @param parentBone defines the parent (can be null if the bone is the root)
  82892. * @param localMatrix defines the local matrix
  82893. * @param restPose defines the rest pose matrix
  82894. * @param baseMatrix defines the base matrix
  82895. * @param index defines index of the bone in the hiearchy
  82896. */
  82897. function Bone(
  82898. /**
  82899. * defines the bone name
  82900. */
  82901. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  82902. if (parentBone === void 0) { parentBone = null; }
  82903. if (localMatrix === void 0) { localMatrix = null; }
  82904. if (restPose === void 0) { restPose = null; }
  82905. if (baseMatrix === void 0) { baseMatrix = null; }
  82906. if (index === void 0) { index = null; }
  82907. var _this = _super.call(this, name, skeleton.getScene()) || this;
  82908. _this.name = name;
  82909. /**
  82910. * Gets the list of child bones
  82911. */
  82912. _this.children = new Array();
  82913. /** Gets the animations associated with this bone */
  82914. _this.animations = new Array();
  82915. /**
  82916. * @hidden Internal only
  82917. * Set this value to map this bone to a different index in the transform matrices
  82918. * Set this value to -1 to exclude the bone from the transform matrices
  82919. */
  82920. _this._index = null;
  82921. _this._absoluteTransform = new BABYLON.Matrix();
  82922. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  82923. _this._scalingDeterminant = 1;
  82924. _this._worldTransform = new BABYLON.Matrix();
  82925. _this._needToDecompose = true;
  82926. _this._needToCompose = false;
  82927. _this._skeleton = skeleton;
  82928. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  82929. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  82930. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  82931. _this._index = index;
  82932. skeleton.bones.push(_this);
  82933. _this.setParent(parentBone, false);
  82934. if (baseMatrix || localMatrix) {
  82935. _this._updateDifferenceMatrix();
  82936. }
  82937. return _this;
  82938. }
  82939. Object.defineProperty(Bone.prototype, "_matrix", {
  82940. /** @hidden */
  82941. get: function () {
  82942. this._compose();
  82943. return this._localMatrix;
  82944. },
  82945. /** @hidden */
  82946. set: function (value) {
  82947. this._localMatrix.copyFrom(value);
  82948. this._needToDecompose = true;
  82949. },
  82950. enumerable: true,
  82951. configurable: true
  82952. });
  82953. // Members
  82954. /**
  82955. * Gets the parent skeleton
  82956. * @returns a skeleton
  82957. */
  82958. Bone.prototype.getSkeleton = function () {
  82959. return this._skeleton;
  82960. };
  82961. /**
  82962. * Gets parent bone
  82963. * @returns a bone or null if the bone is the root of the bone hierarchy
  82964. */
  82965. Bone.prototype.getParent = function () {
  82966. return this._parent;
  82967. };
  82968. /**
  82969. * Sets the parent bone
  82970. * @param parent defines the parent (can be null if the bone is the root)
  82971. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  82972. */
  82973. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  82974. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  82975. if (this._parent === parent) {
  82976. return;
  82977. }
  82978. if (this._parent) {
  82979. var index = this._parent.children.indexOf(this);
  82980. if (index !== -1) {
  82981. this._parent.children.splice(index, 1);
  82982. }
  82983. }
  82984. this._parent = parent;
  82985. if (this._parent) {
  82986. this._parent.children.push(this);
  82987. }
  82988. if (updateDifferenceMatrix) {
  82989. this._updateDifferenceMatrix();
  82990. }
  82991. this.markAsDirty();
  82992. };
  82993. /**
  82994. * Gets the local matrix
  82995. * @returns a matrix
  82996. */
  82997. Bone.prototype.getLocalMatrix = function () {
  82998. this._compose();
  82999. return this._localMatrix;
  83000. };
  83001. /**
  83002. * Gets the base matrix (initial matrix which remains unchanged)
  83003. * @returns a matrix
  83004. */
  83005. Bone.prototype.getBaseMatrix = function () {
  83006. return this._baseMatrix;
  83007. };
  83008. /**
  83009. * Gets the rest pose matrix
  83010. * @returns a matrix
  83011. */
  83012. Bone.prototype.getRestPose = function () {
  83013. return this._restPose;
  83014. };
  83015. /**
  83016. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  83017. */
  83018. Bone.prototype.getWorldMatrix = function () {
  83019. return this._worldTransform;
  83020. };
  83021. /**
  83022. * Sets the local matrix to rest pose matrix
  83023. */
  83024. Bone.prototype.returnToRest = function () {
  83025. this.updateMatrix(this._restPose.clone());
  83026. };
  83027. /**
  83028. * Gets the inverse of the absolute transform matrix.
  83029. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  83030. * @returns a matrix
  83031. */
  83032. Bone.prototype.getInvertedAbsoluteTransform = function () {
  83033. return this._invertedAbsoluteTransform;
  83034. };
  83035. /**
  83036. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  83037. * @returns a matrix
  83038. */
  83039. Bone.prototype.getAbsoluteTransform = function () {
  83040. return this._absoluteTransform;
  83041. };
  83042. Object.defineProperty(Bone.prototype, "position", {
  83043. // Properties (matches AbstractMesh properties)
  83044. /** Gets or sets current position (in local space) */
  83045. get: function () {
  83046. this._decompose();
  83047. return this._localPosition;
  83048. },
  83049. set: function (newPosition) {
  83050. this._decompose();
  83051. this._localPosition.copyFrom(newPosition);
  83052. this._markAsDirtyAndCompose();
  83053. },
  83054. enumerable: true,
  83055. configurable: true
  83056. });
  83057. Object.defineProperty(Bone.prototype, "rotation", {
  83058. /** Gets or sets current rotation (in local space) */
  83059. get: function () {
  83060. return this.getRotation();
  83061. },
  83062. set: function (newRotation) {
  83063. this.setRotation(newRotation);
  83064. },
  83065. enumerable: true,
  83066. configurable: true
  83067. });
  83068. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  83069. /** Gets or sets current rotation quaternion (in local space) */
  83070. get: function () {
  83071. this._decompose();
  83072. return this._localRotation;
  83073. },
  83074. set: function (newRotation) {
  83075. this.setRotationQuaternion(newRotation);
  83076. },
  83077. enumerable: true,
  83078. configurable: true
  83079. });
  83080. Object.defineProperty(Bone.prototype, "scaling", {
  83081. /** Gets or sets current scaling (in local space) */
  83082. get: function () {
  83083. return this.getScale();
  83084. },
  83085. set: function (newScaling) {
  83086. this.setScale(newScaling);
  83087. },
  83088. enumerable: true,
  83089. configurable: true
  83090. });
  83091. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  83092. /**
  83093. * Gets the animation properties override
  83094. */
  83095. get: function () {
  83096. return this._skeleton.animationPropertiesOverride;
  83097. },
  83098. enumerable: true,
  83099. configurable: true
  83100. });
  83101. // Methods
  83102. Bone.prototype._decompose = function () {
  83103. if (!this._needToDecompose) {
  83104. return;
  83105. }
  83106. this._needToDecompose = false;
  83107. if (!this._localScaling) {
  83108. this._localScaling = BABYLON.Vector3.Zero();
  83109. this._localRotation = BABYLON.Quaternion.Zero();
  83110. this._localPosition = BABYLON.Vector3.Zero();
  83111. }
  83112. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  83113. };
  83114. Bone.prototype._compose = function () {
  83115. if (!this._needToCompose) {
  83116. return;
  83117. }
  83118. this._needToCompose = false;
  83119. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  83120. };
  83121. /**
  83122. * Update the base and local matrices
  83123. * @param matrix defines the new base or local matrix
  83124. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  83125. * @param updateLocalMatrix defines if the local matrix should be updated
  83126. */
  83127. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  83128. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  83129. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  83130. this._baseMatrix.copyFrom(matrix);
  83131. if (updateDifferenceMatrix) {
  83132. this._updateDifferenceMatrix();
  83133. }
  83134. if (updateLocalMatrix) {
  83135. this._localMatrix.copyFrom(matrix);
  83136. this._markAsDirtyAndDecompose();
  83137. }
  83138. else {
  83139. this.markAsDirty();
  83140. }
  83141. };
  83142. /** @hidden */
  83143. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  83144. if (updateChildren === void 0) { updateChildren = true; }
  83145. if (!rootMatrix) {
  83146. rootMatrix = this._baseMatrix;
  83147. }
  83148. if (this._parent) {
  83149. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  83150. }
  83151. else {
  83152. this._absoluteTransform.copyFrom(rootMatrix);
  83153. }
  83154. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  83155. if (updateChildren) {
  83156. for (var index = 0; index < this.children.length; index++) {
  83157. this.children[index]._updateDifferenceMatrix();
  83158. }
  83159. }
  83160. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  83161. };
  83162. /**
  83163. * Flag the bone as dirty (Forcing it to update everything)
  83164. */
  83165. Bone.prototype.markAsDirty = function () {
  83166. this._currentRenderId++;
  83167. this._childRenderId++;
  83168. this._skeleton._markAsDirty();
  83169. };
  83170. Bone.prototype._markAsDirtyAndCompose = function () {
  83171. this.markAsDirty();
  83172. this._needToCompose = true;
  83173. };
  83174. Bone.prototype._markAsDirtyAndDecompose = function () {
  83175. this.markAsDirty();
  83176. this._needToDecompose = true;
  83177. };
  83178. /**
  83179. * Copy an animation range from another bone
  83180. * @param source defines the source bone
  83181. * @param rangeName defines the range name to copy
  83182. * @param frameOffset defines the frame offset
  83183. * @param rescaleAsRequired defines if rescaling must be applied if required
  83184. * @param skelDimensionsRatio defines the scaling ratio
  83185. * @returns true if operation was successful
  83186. */
  83187. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  83188. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  83189. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  83190. // all animation may be coming from a library skeleton, so may need to create animation
  83191. if (this.animations.length === 0) {
  83192. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  83193. this.animations[0].setKeys([]);
  83194. }
  83195. // get animation info / verify there is such a range from the source bone
  83196. var sourceRange = source.animations[0].getRange(rangeName);
  83197. if (!sourceRange) {
  83198. return false;
  83199. }
  83200. var from = sourceRange.from;
  83201. var to = sourceRange.to;
  83202. var sourceKeys = source.animations[0].getKeys();
  83203. // rescaling prep
  83204. var sourceBoneLength = source.length;
  83205. var sourceParent = source.getParent();
  83206. var parent = this.getParent();
  83207. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  83208. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  83209. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  83210. var destKeys = this.animations[0].getKeys();
  83211. // loop vars declaration
  83212. var orig;
  83213. var origTranslation;
  83214. var mat;
  83215. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  83216. orig = sourceKeys[key];
  83217. if (orig.frame >= from && orig.frame <= to) {
  83218. if (rescaleAsRequired) {
  83219. mat = orig.value.clone();
  83220. // scale based on parent ratio, when bone has parent
  83221. if (parentScalingReqd) {
  83222. origTranslation = mat.getTranslation();
  83223. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  83224. // scale based on skeleton dimension ratio when root bone, and value is passed
  83225. }
  83226. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  83227. origTranslation = mat.getTranslation();
  83228. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  83229. // use original when root bone, and no data for skelDimensionsRatio
  83230. }
  83231. else {
  83232. mat = orig.value;
  83233. }
  83234. }
  83235. else {
  83236. mat = orig.value;
  83237. }
  83238. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  83239. }
  83240. }
  83241. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  83242. return true;
  83243. };
  83244. /**
  83245. * Translate the bone in local or world space
  83246. * @param vec The amount to translate the bone
  83247. * @param space The space that the translation is in
  83248. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83249. */
  83250. Bone.prototype.translate = function (vec, space, mesh) {
  83251. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83252. var lm = this.getLocalMatrix();
  83253. if (space == BABYLON.Space.LOCAL) {
  83254. lm.m[12] += vec.x;
  83255. lm.m[13] += vec.y;
  83256. lm.m[14] += vec.z;
  83257. }
  83258. else {
  83259. var wm = null;
  83260. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83261. if (mesh) {
  83262. wm = mesh.getWorldMatrix();
  83263. }
  83264. this._skeleton.computeAbsoluteTransforms();
  83265. var tmat = Bone._tmpMats[0];
  83266. var tvec = Bone._tmpVecs[0];
  83267. if (this._parent) {
  83268. if (mesh && wm) {
  83269. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83270. tmat.multiplyToRef(wm, tmat);
  83271. }
  83272. else {
  83273. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83274. }
  83275. }
  83276. tmat.m[12] = 0;
  83277. tmat.m[13] = 0;
  83278. tmat.m[14] = 0;
  83279. tmat.invert();
  83280. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  83281. lm.m[12] += tvec.x;
  83282. lm.m[13] += tvec.y;
  83283. lm.m[14] += tvec.z;
  83284. }
  83285. this._markAsDirtyAndDecompose();
  83286. };
  83287. /**
  83288. * Set the postion of the bone in local or world space
  83289. * @param position The position to set the bone
  83290. * @param space The space that the position is in
  83291. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83292. */
  83293. Bone.prototype.setPosition = function (position, space, mesh) {
  83294. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83295. var lm = this.getLocalMatrix();
  83296. if (space == BABYLON.Space.LOCAL) {
  83297. lm.m[12] = position.x;
  83298. lm.m[13] = position.y;
  83299. lm.m[14] = position.z;
  83300. }
  83301. else {
  83302. var wm = null;
  83303. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83304. if (mesh) {
  83305. wm = mesh.getWorldMatrix();
  83306. }
  83307. this._skeleton.computeAbsoluteTransforms();
  83308. var tmat = Bone._tmpMats[0];
  83309. var vec = Bone._tmpVecs[0];
  83310. if (this._parent) {
  83311. if (mesh && wm) {
  83312. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83313. tmat.multiplyToRef(wm, tmat);
  83314. }
  83315. else {
  83316. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83317. }
  83318. }
  83319. tmat.invert();
  83320. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  83321. lm.m[12] = vec.x;
  83322. lm.m[13] = vec.y;
  83323. lm.m[14] = vec.z;
  83324. }
  83325. this._markAsDirtyAndDecompose();
  83326. };
  83327. /**
  83328. * Set the absolute position of the bone (world space)
  83329. * @param position The position to set the bone
  83330. * @param mesh The mesh that this bone is attached to
  83331. */
  83332. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  83333. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  83334. };
  83335. /**
  83336. * Scale the bone on the x, y and z axes (in local space)
  83337. * @param x The amount to scale the bone on the x axis
  83338. * @param y The amount to scale the bone on the y axis
  83339. * @param z The amount to scale the bone on the z axis
  83340. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  83341. */
  83342. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  83343. if (scaleChildren === void 0) { scaleChildren = false; }
  83344. var locMat = this.getLocalMatrix();
  83345. // Apply new scaling on top of current local matrix
  83346. var scaleMat = Bone._tmpMats[0];
  83347. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  83348. scaleMat.multiplyToRef(locMat, locMat);
  83349. // Invert scaling matrix and apply the inverse to all children
  83350. scaleMat.invert();
  83351. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  83352. var child = _a[_i];
  83353. var cm = child.getLocalMatrix();
  83354. cm.multiplyToRef(scaleMat, cm);
  83355. cm.m[12] *= x;
  83356. cm.m[13] *= y;
  83357. cm.m[14] *= z;
  83358. child._markAsDirtyAndDecompose();
  83359. }
  83360. this._markAsDirtyAndDecompose();
  83361. if (scaleChildren) {
  83362. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  83363. var child = _c[_b];
  83364. child.scale(x, y, z, scaleChildren);
  83365. }
  83366. }
  83367. };
  83368. /**
  83369. * Set the bone scaling in local space
  83370. * @param scale defines the scaling vector
  83371. */
  83372. Bone.prototype.setScale = function (scale) {
  83373. this._decompose();
  83374. this._localScaling.copyFrom(scale);
  83375. this._markAsDirtyAndCompose();
  83376. };
  83377. /**
  83378. * Gets the current scaling in local space
  83379. * @returns the current scaling vector
  83380. */
  83381. Bone.prototype.getScale = function () {
  83382. this._decompose();
  83383. return this._localScaling;
  83384. };
  83385. /**
  83386. * Gets the current scaling in local space and stores it in a target vector
  83387. * @param result defines the target vector
  83388. */
  83389. Bone.prototype.getScaleToRef = function (result) {
  83390. this._decompose();
  83391. result.copyFrom(this._localScaling);
  83392. };
  83393. /**
  83394. * Set the yaw, pitch, and roll of the bone in local or world space
  83395. * @param yaw The rotation of the bone on the y axis
  83396. * @param pitch The rotation of the bone on the x axis
  83397. * @param roll The rotation of the bone on the z axis
  83398. * @param space The space that the axes of rotation are in
  83399. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83400. */
  83401. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  83402. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83403. if (space === BABYLON.Space.LOCAL) {
  83404. var quat = Bone._tmpQuat;
  83405. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  83406. this.setRotationQuaternion(quat, space, mesh);
  83407. return;
  83408. }
  83409. var rotMatInv = Bone._tmpMats[0];
  83410. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  83411. return;
  83412. }
  83413. var rotMat = Bone._tmpMats[1];
  83414. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  83415. rotMatInv.multiplyToRef(rotMat, rotMat);
  83416. this._rotateWithMatrix(rotMat, space, mesh);
  83417. };
  83418. /**
  83419. * Add a rotation to the bone on an axis in local or world space
  83420. * @param axis The axis to rotate the bone on
  83421. * @param amount The amount to rotate the bone
  83422. * @param space The space that the axis is in
  83423. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83424. */
  83425. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  83426. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83427. var rmat = Bone._tmpMats[0];
  83428. rmat.m[12] = 0;
  83429. rmat.m[13] = 0;
  83430. rmat.m[14] = 0;
  83431. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  83432. this._rotateWithMatrix(rmat, space, mesh);
  83433. };
  83434. /**
  83435. * Set the rotation of the bone to a particular axis angle in local or world space
  83436. * @param axis The axis to rotate the bone on
  83437. * @param angle The angle that the bone should be rotated to
  83438. * @param space The space that the axis is in
  83439. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83440. */
  83441. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  83442. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83443. if (space === BABYLON.Space.LOCAL) {
  83444. var quat = Bone._tmpQuat;
  83445. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  83446. this.setRotationQuaternion(quat, space, mesh);
  83447. return;
  83448. }
  83449. var rotMatInv = Bone._tmpMats[0];
  83450. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  83451. return;
  83452. }
  83453. var rotMat = Bone._tmpMats[1];
  83454. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  83455. rotMatInv.multiplyToRef(rotMat, rotMat);
  83456. this._rotateWithMatrix(rotMat, space, mesh);
  83457. };
  83458. /**
  83459. * Set the euler rotation of the bone in local of world space
  83460. * @param rotation The euler rotation that the bone should be set to
  83461. * @param space The space that the rotation is in
  83462. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83463. */
  83464. Bone.prototype.setRotation = function (rotation, space, mesh) {
  83465. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83466. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  83467. };
  83468. /**
  83469. * Set the quaternion rotation of the bone in local of world space
  83470. * @param quat The quaternion rotation that the bone should be set to
  83471. * @param space The space that the rotation is in
  83472. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83473. */
  83474. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  83475. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83476. if (space === BABYLON.Space.LOCAL) {
  83477. this._decompose();
  83478. this._localRotation.copyFrom(quat);
  83479. this._markAsDirtyAndCompose();
  83480. return;
  83481. }
  83482. var rotMatInv = Bone._tmpMats[0];
  83483. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  83484. return;
  83485. }
  83486. var rotMat = Bone._tmpMats[1];
  83487. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  83488. rotMatInv.multiplyToRef(rotMat, rotMat);
  83489. this._rotateWithMatrix(rotMat, space, mesh);
  83490. };
  83491. /**
  83492. * Set the rotation matrix of the bone in local of world space
  83493. * @param rotMat The rotation matrix that the bone should be set to
  83494. * @param space The space that the rotation is in
  83495. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83496. */
  83497. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  83498. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83499. if (space === BABYLON.Space.LOCAL) {
  83500. var quat = Bone._tmpQuat;
  83501. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  83502. this.setRotationQuaternion(quat, space, mesh);
  83503. return;
  83504. }
  83505. var rotMatInv = Bone._tmpMats[0];
  83506. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  83507. return;
  83508. }
  83509. var rotMat2 = Bone._tmpMats[1];
  83510. rotMat2.copyFrom(rotMat);
  83511. rotMatInv.multiplyToRef(rotMat, rotMat2);
  83512. this._rotateWithMatrix(rotMat2, space, mesh);
  83513. };
  83514. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  83515. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83516. var lmat = this.getLocalMatrix();
  83517. var lx = lmat.m[12];
  83518. var ly = lmat.m[13];
  83519. var lz = lmat.m[14];
  83520. var parent = this.getParent();
  83521. var parentScale = Bone._tmpMats[3];
  83522. var parentScaleInv = Bone._tmpMats[4];
  83523. if (parent && space == BABYLON.Space.WORLD) {
  83524. if (mesh) {
  83525. parentScale.copyFrom(mesh.getWorldMatrix());
  83526. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  83527. }
  83528. else {
  83529. parentScale.copyFrom(parent.getAbsoluteTransform());
  83530. }
  83531. parentScaleInv.copyFrom(parentScale);
  83532. parentScaleInv.invert();
  83533. lmat.multiplyToRef(parentScale, lmat);
  83534. lmat.multiplyToRef(rmat, lmat);
  83535. lmat.multiplyToRef(parentScaleInv, lmat);
  83536. }
  83537. else {
  83538. if (space == BABYLON.Space.WORLD && mesh) {
  83539. parentScale.copyFrom(mesh.getWorldMatrix());
  83540. parentScaleInv.copyFrom(parentScale);
  83541. parentScaleInv.invert();
  83542. lmat.multiplyToRef(parentScale, lmat);
  83543. lmat.multiplyToRef(rmat, lmat);
  83544. lmat.multiplyToRef(parentScaleInv, lmat);
  83545. }
  83546. else {
  83547. lmat.multiplyToRef(rmat, lmat);
  83548. }
  83549. }
  83550. lmat.m[12] = lx;
  83551. lmat.m[13] = ly;
  83552. lmat.m[14] = lz;
  83553. this.computeAbsoluteTransforms();
  83554. this._markAsDirtyAndDecompose();
  83555. };
  83556. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  83557. var scaleMatrix = Bone._tmpMats[2];
  83558. rotMatInv.copyFrom(this.getAbsoluteTransform());
  83559. if (mesh) {
  83560. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  83561. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  83562. }
  83563. rotMatInv.invert();
  83564. if (isNaN(rotMatInv.m[0])) {
  83565. // Matrix failed to invert.
  83566. // This can happen if scale is zero for example.
  83567. return false;
  83568. }
  83569. scaleMatrix.m[0] *= this._scalingDeterminant;
  83570. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  83571. return true;
  83572. };
  83573. /**
  83574. * Get the position of the bone in local or world space
  83575. * @param space The space that the returned position is in
  83576. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83577. * @returns The position of the bone
  83578. */
  83579. Bone.prototype.getPosition = function (space, mesh) {
  83580. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83581. if (mesh === void 0) { mesh = null; }
  83582. var pos = BABYLON.Vector3.Zero();
  83583. this.getPositionToRef(space, mesh, pos);
  83584. return pos;
  83585. };
  83586. /**
  83587. * Copy the position of the bone to a vector3 in local or world space
  83588. * @param space The space that the returned position is in
  83589. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83590. * @param result The vector3 to copy the position to
  83591. */
  83592. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  83593. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83594. if (space == BABYLON.Space.LOCAL) {
  83595. var lm = this.getLocalMatrix();
  83596. result.x = lm.m[12];
  83597. result.y = lm.m[13];
  83598. result.z = lm.m[14];
  83599. }
  83600. else {
  83601. var wm = null;
  83602. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83603. if (mesh) {
  83604. wm = mesh.getWorldMatrix();
  83605. }
  83606. this._skeleton.computeAbsoluteTransforms();
  83607. var tmat = Bone._tmpMats[0];
  83608. if (mesh && wm) {
  83609. tmat.copyFrom(this.getAbsoluteTransform());
  83610. tmat.multiplyToRef(wm, tmat);
  83611. }
  83612. else {
  83613. tmat = this.getAbsoluteTransform();
  83614. }
  83615. result.x = tmat.m[12];
  83616. result.y = tmat.m[13];
  83617. result.z = tmat.m[14];
  83618. }
  83619. };
  83620. /**
  83621. * Get the absolute position of the bone (world space)
  83622. * @param mesh The mesh that this bone is attached to
  83623. * @returns The absolute position of the bone
  83624. */
  83625. Bone.prototype.getAbsolutePosition = function (mesh) {
  83626. if (mesh === void 0) { mesh = null; }
  83627. var pos = BABYLON.Vector3.Zero();
  83628. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  83629. return pos;
  83630. };
  83631. /**
  83632. * Copy the absolute position of the bone (world space) to the result param
  83633. * @param mesh The mesh that this bone is attached to
  83634. * @param result The vector3 to copy the absolute position to
  83635. */
  83636. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  83637. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  83638. };
  83639. /**
  83640. * Compute the absolute transforms of this bone and its children
  83641. */
  83642. Bone.prototype.computeAbsoluteTransforms = function () {
  83643. this._compose();
  83644. if (this._parent) {
  83645. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  83646. }
  83647. else {
  83648. this._absoluteTransform.copyFrom(this._localMatrix);
  83649. var poseMatrix = this._skeleton.getPoseMatrix();
  83650. if (poseMatrix) {
  83651. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  83652. }
  83653. }
  83654. var children = this.children;
  83655. var len = children.length;
  83656. for (var i = 0; i < len; i++) {
  83657. children[i].computeAbsoluteTransforms();
  83658. }
  83659. };
  83660. /**
  83661. * Get the world direction from an axis that is in the local space of the bone
  83662. * @param localAxis The local direction that is used to compute the world direction
  83663. * @param mesh The mesh that this bone is attached to
  83664. * @returns The world direction
  83665. */
  83666. Bone.prototype.getDirection = function (localAxis, mesh) {
  83667. if (mesh === void 0) { mesh = null; }
  83668. var result = BABYLON.Vector3.Zero();
  83669. this.getDirectionToRef(localAxis, mesh, result);
  83670. return result;
  83671. };
  83672. /**
  83673. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  83674. * @param localAxis The local direction that is used to compute the world direction
  83675. * @param mesh The mesh that this bone is attached to
  83676. * @param result The vector3 that the world direction will be copied to
  83677. */
  83678. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  83679. if (mesh === void 0) { mesh = null; }
  83680. var wm = null;
  83681. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83682. if (mesh) {
  83683. wm = mesh.getWorldMatrix();
  83684. }
  83685. this._skeleton.computeAbsoluteTransforms();
  83686. var mat = Bone._tmpMats[0];
  83687. mat.copyFrom(this.getAbsoluteTransform());
  83688. if (mesh && wm) {
  83689. mat.multiplyToRef(wm, mat);
  83690. }
  83691. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  83692. result.normalize();
  83693. };
  83694. /**
  83695. * Get the euler rotation of the bone in local or world space
  83696. * @param space The space that the rotation should be in
  83697. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83698. * @returns The euler rotation
  83699. */
  83700. Bone.prototype.getRotation = function (space, mesh) {
  83701. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83702. if (mesh === void 0) { mesh = null; }
  83703. var result = BABYLON.Vector3.Zero();
  83704. this.getRotationToRef(space, mesh, result);
  83705. return result;
  83706. };
  83707. /**
  83708. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  83709. * @param space The space that the rotation should be in
  83710. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83711. * @param result The vector3 that the rotation should be copied to
  83712. */
  83713. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  83714. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83715. if (mesh === void 0) { mesh = null; }
  83716. var quat = Bone._tmpQuat;
  83717. this.getRotationQuaternionToRef(space, mesh, quat);
  83718. quat.toEulerAnglesToRef(result);
  83719. };
  83720. /**
  83721. * Get the quaternion rotation of the bone in either local or world space
  83722. * @param space The space that the rotation should be in
  83723. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83724. * @returns The quaternion rotation
  83725. */
  83726. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  83727. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83728. if (mesh === void 0) { mesh = null; }
  83729. var result = BABYLON.Quaternion.Identity();
  83730. this.getRotationQuaternionToRef(space, mesh, result);
  83731. return result;
  83732. };
  83733. /**
  83734. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  83735. * @param space The space that the rotation should be in
  83736. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83737. * @param result The quaternion that the rotation should be copied to
  83738. */
  83739. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  83740. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83741. if (mesh === void 0) { mesh = null; }
  83742. if (space == BABYLON.Space.LOCAL) {
  83743. this._decompose();
  83744. result.copyFrom(this._localRotation);
  83745. }
  83746. else {
  83747. var mat = Bone._tmpMats[0];
  83748. var amat = this.getAbsoluteTransform();
  83749. if (mesh) {
  83750. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  83751. }
  83752. else {
  83753. mat.copyFrom(amat);
  83754. }
  83755. mat.m[0] *= this._scalingDeterminant;
  83756. mat.m[1] *= this._scalingDeterminant;
  83757. mat.m[2] *= this._scalingDeterminant;
  83758. mat.decompose(undefined, result, undefined);
  83759. }
  83760. };
  83761. /**
  83762. * Get the rotation matrix of the bone in local or world space
  83763. * @param space The space that the rotation should be in
  83764. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83765. * @returns The rotation matrix
  83766. */
  83767. Bone.prototype.getRotationMatrix = function (space, mesh) {
  83768. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83769. var result = BABYLON.Matrix.Identity();
  83770. this.getRotationMatrixToRef(space, mesh, result);
  83771. return result;
  83772. };
  83773. /**
  83774. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  83775. * @param space The space that the rotation should be in
  83776. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83777. * @param result The quaternion that the rotation should be copied to
  83778. */
  83779. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  83780. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83781. if (space == BABYLON.Space.LOCAL) {
  83782. this.getLocalMatrix().getRotationMatrixToRef(result);
  83783. }
  83784. else {
  83785. var mat = Bone._tmpMats[0];
  83786. var amat = this.getAbsoluteTransform();
  83787. if (mesh) {
  83788. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  83789. }
  83790. else {
  83791. mat.copyFrom(amat);
  83792. }
  83793. mat.m[0] *= this._scalingDeterminant;
  83794. mat.m[1] *= this._scalingDeterminant;
  83795. mat.m[2] *= this._scalingDeterminant;
  83796. mat.getRotationMatrixToRef(result);
  83797. }
  83798. };
  83799. /**
  83800. * Get the world position of a point that is in the local space of the bone
  83801. * @param position The local position
  83802. * @param mesh The mesh that this bone is attached to
  83803. * @returns The world position
  83804. */
  83805. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  83806. if (mesh === void 0) { mesh = null; }
  83807. var result = BABYLON.Vector3.Zero();
  83808. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  83809. return result;
  83810. };
  83811. /**
  83812. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  83813. * @param position The local position
  83814. * @param mesh The mesh that this bone is attached to
  83815. * @param result The vector3 that the world position should be copied to
  83816. */
  83817. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  83818. if (mesh === void 0) { mesh = null; }
  83819. var wm = null;
  83820. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83821. if (mesh) {
  83822. wm = mesh.getWorldMatrix();
  83823. }
  83824. this._skeleton.computeAbsoluteTransforms();
  83825. var tmat = Bone._tmpMats[0];
  83826. if (mesh && wm) {
  83827. tmat.copyFrom(this.getAbsoluteTransform());
  83828. tmat.multiplyToRef(wm, tmat);
  83829. }
  83830. else {
  83831. tmat = this.getAbsoluteTransform();
  83832. }
  83833. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  83834. };
  83835. /**
  83836. * Get the local position of a point that is in world space
  83837. * @param position The world position
  83838. * @param mesh The mesh that this bone is attached to
  83839. * @returns The local position
  83840. */
  83841. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  83842. if (mesh === void 0) { mesh = null; }
  83843. var result = BABYLON.Vector3.Zero();
  83844. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  83845. return result;
  83846. };
  83847. /**
  83848. * Get the local position of a point that is in world space and copy it to the result param
  83849. * @param position The world position
  83850. * @param mesh The mesh that this bone is attached to
  83851. * @param result The vector3 that the local position should be copied to
  83852. */
  83853. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  83854. if (mesh === void 0) { mesh = null; }
  83855. var wm = null;
  83856. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83857. if (mesh) {
  83858. wm = mesh.getWorldMatrix();
  83859. }
  83860. this._skeleton.computeAbsoluteTransforms();
  83861. var tmat = Bone._tmpMats[0];
  83862. tmat.copyFrom(this.getAbsoluteTransform());
  83863. if (mesh && wm) {
  83864. tmat.multiplyToRef(wm, tmat);
  83865. }
  83866. tmat.invert();
  83867. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  83868. };
  83869. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83870. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  83871. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  83872. return Bone;
  83873. }(BABYLON.Node));
  83874. BABYLON.Bone = Bone;
  83875. })(BABYLON || (BABYLON = {}));
  83876. //# sourceMappingURL=babylon.bone.js.map
  83877. var BABYLON;
  83878. (function (BABYLON) {
  83879. /**
  83880. * Class used to apply inverse kinematics to bones
  83881. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  83882. */
  83883. var BoneIKController = /** @class */ (function () {
  83884. /**
  83885. * Creates a new BoneIKController
  83886. * @param mesh defines the mesh to control
  83887. * @param bone defines the bone to control
  83888. * @param options defines options to set up the controller
  83889. */
  83890. function BoneIKController(mesh, bone, options) {
  83891. /**
  83892. * Gets or sets the target position
  83893. */
  83894. this.targetPosition = BABYLON.Vector3.Zero();
  83895. /**
  83896. * Gets or sets the pole target position
  83897. */
  83898. this.poleTargetPosition = BABYLON.Vector3.Zero();
  83899. /**
  83900. * Gets or sets the pole target local offset
  83901. */
  83902. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  83903. /**
  83904. * Gets or sets the pole angle
  83905. */
  83906. this.poleAngle = 0;
  83907. /**
  83908. * 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)
  83909. */
  83910. this.slerpAmount = 1;
  83911. this._bone1Quat = BABYLON.Quaternion.Identity();
  83912. this._bone1Mat = BABYLON.Matrix.Identity();
  83913. this._bone2Ang = Math.PI;
  83914. this._maxAngle = Math.PI;
  83915. this._rightHandedSystem = false;
  83916. this._bendAxis = BABYLON.Vector3.Right();
  83917. this._slerping = false;
  83918. this._adjustRoll = 0;
  83919. this._bone2 = bone;
  83920. this._bone1 = bone.getParent();
  83921. if (!this._bone1) {
  83922. return;
  83923. }
  83924. this.mesh = mesh;
  83925. var bonePos = bone.getPosition();
  83926. if (bone.getAbsoluteTransform().determinant() > 0) {
  83927. this._rightHandedSystem = true;
  83928. this._bendAxis.x = 0;
  83929. this._bendAxis.y = 0;
  83930. this._bendAxis.z = -1;
  83931. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  83932. this._adjustRoll = Math.PI * .5;
  83933. this._bendAxis.z = 1;
  83934. }
  83935. }
  83936. if (this._bone1.length) {
  83937. var boneScale1 = this._bone1.getScale();
  83938. var boneScale2 = this._bone2.getScale();
  83939. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  83940. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  83941. }
  83942. else if (this._bone1.children[0]) {
  83943. mesh.computeWorldMatrix(true);
  83944. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  83945. var pos2 = this._bone2.getAbsolutePosition(mesh);
  83946. var pos3 = this._bone1.getAbsolutePosition(mesh);
  83947. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  83948. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  83949. }
  83950. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  83951. this.maxAngle = Math.PI;
  83952. if (options) {
  83953. if (options.targetMesh) {
  83954. this.targetMesh = options.targetMesh;
  83955. this.targetMesh.computeWorldMatrix(true);
  83956. }
  83957. if (options.poleTargetMesh) {
  83958. this.poleTargetMesh = options.poleTargetMesh;
  83959. this.poleTargetMesh.computeWorldMatrix(true);
  83960. }
  83961. else if (options.poleTargetBone) {
  83962. this.poleTargetBone = options.poleTargetBone;
  83963. }
  83964. else if (this._bone1.getParent()) {
  83965. this.poleTargetBone = this._bone1.getParent();
  83966. }
  83967. if (options.poleTargetLocalOffset) {
  83968. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  83969. }
  83970. if (options.poleAngle) {
  83971. this.poleAngle = options.poleAngle;
  83972. }
  83973. if (options.bendAxis) {
  83974. this._bendAxis.copyFrom(options.bendAxis);
  83975. }
  83976. if (options.maxAngle) {
  83977. this.maxAngle = options.maxAngle;
  83978. }
  83979. if (options.slerpAmount) {
  83980. this.slerpAmount = options.slerpAmount;
  83981. }
  83982. }
  83983. }
  83984. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  83985. /**
  83986. * Gets or sets maximum allowed angle
  83987. */
  83988. get: function () {
  83989. return this._maxAngle;
  83990. },
  83991. set: function (value) {
  83992. this._setMaxAngle(value);
  83993. },
  83994. enumerable: true,
  83995. configurable: true
  83996. });
  83997. BoneIKController.prototype._setMaxAngle = function (ang) {
  83998. if (ang < 0) {
  83999. ang = 0;
  84000. }
  84001. if (ang > Math.PI || ang == undefined) {
  84002. ang = Math.PI;
  84003. }
  84004. this._maxAngle = ang;
  84005. var a = this._bone1Length;
  84006. var b = this._bone2Length;
  84007. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  84008. };
  84009. /**
  84010. * Force the controller to update the bones
  84011. */
  84012. BoneIKController.prototype.update = function () {
  84013. var bone1 = this._bone1;
  84014. if (!bone1) {
  84015. return;
  84016. }
  84017. var target = this.targetPosition;
  84018. var poleTarget = this.poleTargetPosition;
  84019. var mat1 = BoneIKController._tmpMats[0];
  84020. var mat2 = BoneIKController._tmpMats[1];
  84021. if (this.targetMesh) {
  84022. target.copyFrom(this.targetMesh.getAbsolutePosition());
  84023. }
  84024. if (this.poleTargetBone) {
  84025. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  84026. }
  84027. else if (this.poleTargetMesh) {
  84028. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  84029. }
  84030. var bonePos = BoneIKController._tmpVecs[0];
  84031. var zaxis = BoneIKController._tmpVecs[1];
  84032. var xaxis = BoneIKController._tmpVecs[2];
  84033. var yaxis = BoneIKController._tmpVecs[3];
  84034. var upAxis = BoneIKController._tmpVecs[4];
  84035. var _tmpQuat = BoneIKController._tmpQuat;
  84036. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  84037. poleTarget.subtractToRef(bonePos, upAxis);
  84038. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  84039. upAxis.y = 1;
  84040. }
  84041. else {
  84042. upAxis.normalize();
  84043. }
  84044. target.subtractToRef(bonePos, yaxis);
  84045. yaxis.normalize();
  84046. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  84047. zaxis.normalize();
  84048. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  84049. xaxis.normalize();
  84050. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  84051. var a = this._bone1Length;
  84052. var b = this._bone2Length;
  84053. var c = BABYLON.Vector3.Distance(bonePos, target);
  84054. if (this._maxReach > 0) {
  84055. c = Math.min(this._maxReach, c);
  84056. }
  84057. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  84058. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  84059. if (acosa > 1) {
  84060. acosa = 1;
  84061. }
  84062. if (acosb > 1) {
  84063. acosb = 1;
  84064. }
  84065. if (acosa < -1) {
  84066. acosa = -1;
  84067. }
  84068. if (acosb < -1) {
  84069. acosb = -1;
  84070. }
  84071. var angA = Math.acos(acosa);
  84072. var angB = Math.acos(acosb);
  84073. var angC = -angA - angB;
  84074. if (this._rightHandedSystem) {
  84075. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  84076. mat2.multiplyToRef(mat1, mat1);
  84077. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  84078. mat2.multiplyToRef(mat1, mat1);
  84079. }
  84080. else {
  84081. var _tmpVec = BoneIKController._tmpVecs[5];
  84082. _tmpVec.copyFrom(this._bendAxis);
  84083. _tmpVec.x *= -1;
  84084. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  84085. mat2.multiplyToRef(mat1, mat1);
  84086. }
  84087. if (this.poleAngle) {
  84088. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  84089. mat1.multiplyToRef(mat2, mat1);
  84090. }
  84091. if (this._bone1) {
  84092. if (this.slerpAmount < 1) {
  84093. if (!this._slerping) {
  84094. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  84095. }
  84096. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  84097. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  84098. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  84099. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  84100. this._slerping = true;
  84101. }
  84102. else {
  84103. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  84104. this._bone1Mat.copyFrom(mat1);
  84105. this._slerping = false;
  84106. }
  84107. }
  84108. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  84109. this._bone2Ang = angC;
  84110. };
  84111. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84112. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  84113. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  84114. return BoneIKController;
  84115. }());
  84116. BABYLON.BoneIKController = BoneIKController;
  84117. })(BABYLON || (BABYLON = {}));
  84118. //# sourceMappingURL=babylon.boneIKController.js.map
  84119. var BABYLON;
  84120. (function (BABYLON) {
  84121. /**
  84122. * Class used to make a bone look toward a point in space
  84123. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  84124. */
  84125. var BoneLookController = /** @class */ (function () {
  84126. /**
  84127. * Create a BoneLookController
  84128. * @param mesh the mesh that the bone belongs to
  84129. * @param bone the bone that will be looking to the target
  84130. * @param target the target Vector3 to look at
  84131. * @param settings optional settings:
  84132. * * maxYaw: the maximum angle the bone will yaw to
  84133. * * minYaw: the minimum angle the bone will yaw to
  84134. * * maxPitch: the maximum angle the bone will pitch to
  84135. * * minPitch: the minimum angle the bone will yaw to
  84136. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  84137. * * upAxis: the up axis of the coordinate system
  84138. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  84139. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  84140. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  84141. * * adjustYaw: used to make an adjustment to the yaw of the bone
  84142. * * adjustPitch: used to make an adjustment to the pitch of the bone
  84143. * * adjustRoll: used to make an adjustment to the roll of the bone
  84144. **/
  84145. function BoneLookController(mesh, bone, target, options) {
  84146. /**
  84147. * The up axis of the coordinate system that is used when the bone is rotated
  84148. */
  84149. this.upAxis = BABYLON.Vector3.Up();
  84150. /**
  84151. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  84152. */
  84153. this.upAxisSpace = BABYLON.Space.LOCAL;
  84154. /**
  84155. * Used to make an adjustment to the yaw of the bone
  84156. */
  84157. this.adjustYaw = 0;
  84158. /**
  84159. * Used to make an adjustment to the pitch of the bone
  84160. */
  84161. this.adjustPitch = 0;
  84162. /**
  84163. * Used to make an adjustment to the roll of the bone
  84164. */
  84165. this.adjustRoll = 0;
  84166. /**
  84167. * 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)
  84168. */
  84169. this.slerpAmount = 1;
  84170. this._boneQuat = BABYLON.Quaternion.Identity();
  84171. this._slerping = false;
  84172. this._firstFrameSkipped = false;
  84173. this._fowardAxis = BABYLON.Vector3.Forward();
  84174. this.mesh = mesh;
  84175. this.bone = bone;
  84176. this.target = target;
  84177. if (options) {
  84178. if (options.adjustYaw) {
  84179. this.adjustYaw = options.adjustYaw;
  84180. }
  84181. if (options.adjustPitch) {
  84182. this.adjustPitch = options.adjustPitch;
  84183. }
  84184. if (options.adjustRoll) {
  84185. this.adjustRoll = options.adjustRoll;
  84186. }
  84187. if (options.maxYaw != null) {
  84188. this.maxYaw = options.maxYaw;
  84189. }
  84190. else {
  84191. this.maxYaw = Math.PI;
  84192. }
  84193. if (options.minYaw != null) {
  84194. this.minYaw = options.minYaw;
  84195. }
  84196. else {
  84197. this.minYaw = -Math.PI;
  84198. }
  84199. if (options.maxPitch != null) {
  84200. this.maxPitch = options.maxPitch;
  84201. }
  84202. else {
  84203. this.maxPitch = Math.PI;
  84204. }
  84205. if (options.minPitch != null) {
  84206. this.minPitch = options.minPitch;
  84207. }
  84208. else {
  84209. this.minPitch = -Math.PI;
  84210. }
  84211. if (options.slerpAmount != null) {
  84212. this.slerpAmount = options.slerpAmount;
  84213. }
  84214. if (options.upAxis != null) {
  84215. this.upAxis = options.upAxis;
  84216. }
  84217. if (options.upAxisSpace != null) {
  84218. this.upAxisSpace = options.upAxisSpace;
  84219. }
  84220. if (options.yawAxis != null || options.pitchAxis != null) {
  84221. var newYawAxis = BABYLON.Axis.Y;
  84222. var newPitchAxis = BABYLON.Axis.X;
  84223. if (options.yawAxis != null) {
  84224. newYawAxis = options.yawAxis.clone();
  84225. newYawAxis.normalize();
  84226. }
  84227. if (options.pitchAxis != null) {
  84228. newPitchAxis = options.pitchAxis.clone();
  84229. newPitchAxis.normalize();
  84230. }
  84231. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  84232. this._transformYawPitch = BABYLON.Matrix.Identity();
  84233. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  84234. this._transformYawPitchInv = this._transformYawPitch.clone();
  84235. this._transformYawPitch.invert();
  84236. }
  84237. }
  84238. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  84239. this.upAxisSpace = BABYLON.Space.LOCAL;
  84240. }
  84241. }
  84242. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  84243. /**
  84244. * Gets or sets the minimum yaw angle that the bone can look to
  84245. */
  84246. get: function () {
  84247. return this._minYaw;
  84248. },
  84249. set: function (value) {
  84250. this._minYaw = value;
  84251. this._minYawSin = Math.sin(value);
  84252. this._minYawCos = Math.cos(value);
  84253. if (this._maxYaw != null) {
  84254. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  84255. this._yawRange = this._maxYaw - this._minYaw;
  84256. }
  84257. },
  84258. enumerable: true,
  84259. configurable: true
  84260. });
  84261. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  84262. /**
  84263. * Gets or sets the maximum yaw angle that the bone can look to
  84264. */
  84265. get: function () {
  84266. return this._maxYaw;
  84267. },
  84268. set: function (value) {
  84269. this._maxYaw = value;
  84270. this._maxYawSin = Math.sin(value);
  84271. this._maxYawCos = Math.cos(value);
  84272. if (this._minYaw != null) {
  84273. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  84274. this._yawRange = this._maxYaw - this._minYaw;
  84275. }
  84276. },
  84277. enumerable: true,
  84278. configurable: true
  84279. });
  84280. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  84281. /**
  84282. * Gets or sets the minimum pitch angle that the bone can look to
  84283. */
  84284. get: function () {
  84285. return this._minPitch;
  84286. },
  84287. set: function (value) {
  84288. this._minPitch = value;
  84289. this._minPitchTan = Math.tan(value);
  84290. },
  84291. enumerable: true,
  84292. configurable: true
  84293. });
  84294. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  84295. /**
  84296. * Gets or sets the maximum pitch angle that the bone can look to
  84297. */
  84298. get: function () {
  84299. return this._maxPitch;
  84300. },
  84301. set: function (value) {
  84302. this._maxPitch = value;
  84303. this._maxPitchTan = Math.tan(value);
  84304. },
  84305. enumerable: true,
  84306. configurable: true
  84307. });
  84308. /**
  84309. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  84310. */
  84311. BoneLookController.prototype.update = function () {
  84312. //skip the first frame when slerping so that the mesh rotation is correct
  84313. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  84314. this._firstFrameSkipped = true;
  84315. return;
  84316. }
  84317. var bone = this.bone;
  84318. var bonePos = BoneLookController._tmpVecs[0];
  84319. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  84320. var target = this.target;
  84321. var _tmpMat1 = BoneLookController._tmpMats[0];
  84322. var _tmpMat2 = BoneLookController._tmpMats[1];
  84323. var mesh = this.mesh;
  84324. var parentBone = bone.getParent();
  84325. var upAxis = BoneLookController._tmpVecs[1];
  84326. upAxis.copyFrom(this.upAxis);
  84327. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  84328. if (this._transformYawPitch) {
  84329. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  84330. }
  84331. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  84332. }
  84333. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  84334. mesh.getDirectionToRef(upAxis, upAxis);
  84335. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  84336. upAxis.normalize();
  84337. }
  84338. }
  84339. var checkYaw = false;
  84340. var checkPitch = false;
  84341. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  84342. checkYaw = true;
  84343. }
  84344. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  84345. checkPitch = true;
  84346. }
  84347. if (checkYaw || checkPitch) {
  84348. var spaceMat = BoneLookController._tmpMats[2];
  84349. var spaceMatInv = BoneLookController._tmpMats[3];
  84350. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  84351. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  84352. }
  84353. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  84354. spaceMat.copyFrom(mesh.getWorldMatrix());
  84355. }
  84356. else {
  84357. var forwardAxis = BoneLookController._tmpVecs[2];
  84358. forwardAxis.copyFrom(this._fowardAxis);
  84359. if (this._transformYawPitch) {
  84360. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  84361. }
  84362. if (parentBone) {
  84363. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  84364. }
  84365. else {
  84366. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  84367. }
  84368. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  84369. rightAxis.normalize();
  84370. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  84371. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  84372. }
  84373. spaceMat.invertToRef(spaceMatInv);
  84374. var xzlen = null;
  84375. if (checkPitch) {
  84376. var localTarget = BoneLookController._tmpVecs[3];
  84377. target.subtractToRef(bonePos, localTarget);
  84378. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  84379. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  84380. var pitch = Math.atan2(localTarget.y, xzlen);
  84381. var newPitch = pitch;
  84382. if (pitch > this._maxPitch) {
  84383. localTarget.y = this._maxPitchTan * xzlen;
  84384. newPitch = this._maxPitch;
  84385. }
  84386. else if (pitch < this._minPitch) {
  84387. localTarget.y = this._minPitchTan * xzlen;
  84388. newPitch = this._minPitch;
  84389. }
  84390. if (pitch != newPitch) {
  84391. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  84392. localTarget.addInPlace(bonePos);
  84393. target = localTarget;
  84394. }
  84395. }
  84396. if (checkYaw) {
  84397. var localTarget = BoneLookController._tmpVecs[4];
  84398. target.subtractToRef(bonePos, localTarget);
  84399. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  84400. var yaw = Math.atan2(localTarget.x, localTarget.z);
  84401. var newYaw = yaw;
  84402. if (yaw > this._maxYaw || yaw < this._minYaw) {
  84403. if (xzlen == null) {
  84404. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  84405. }
  84406. if (this._yawRange > Math.PI) {
  84407. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  84408. localTarget.z = this._maxYawCos * xzlen;
  84409. localTarget.x = this._maxYawSin * xzlen;
  84410. newYaw = this._maxYaw;
  84411. }
  84412. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  84413. localTarget.z = this._minYawCos * xzlen;
  84414. localTarget.x = this._minYawSin * xzlen;
  84415. newYaw = this._minYaw;
  84416. }
  84417. }
  84418. else {
  84419. if (yaw > this._maxYaw) {
  84420. localTarget.z = this._maxYawCos * xzlen;
  84421. localTarget.x = this._maxYawSin * xzlen;
  84422. newYaw = this._maxYaw;
  84423. }
  84424. else if (yaw < this._minYaw) {
  84425. localTarget.z = this._minYawCos * xzlen;
  84426. localTarget.x = this._minYawSin * xzlen;
  84427. newYaw = this._minYaw;
  84428. }
  84429. }
  84430. }
  84431. if (this._slerping && this._yawRange > Math.PI) {
  84432. //are we going to be crossing into the min/max region?
  84433. var boneFwd = BoneLookController._tmpVecs[8];
  84434. boneFwd.copyFrom(BABYLON.Axis.Z);
  84435. if (this._transformYawPitch) {
  84436. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  84437. }
  84438. var boneRotMat = BoneLookController._tmpMats[4];
  84439. this._boneQuat.toRotationMatrix(boneRotMat);
  84440. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  84441. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  84442. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  84443. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  84444. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  84445. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  84446. if (angBtwTar > angBtwMidYaw) {
  84447. if (xzlen == null) {
  84448. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  84449. }
  84450. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  84451. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  84452. if (angBtwMin < angBtwMax) {
  84453. newYaw = boneYaw + Math.PI * .75;
  84454. localTarget.z = Math.cos(newYaw) * xzlen;
  84455. localTarget.x = Math.sin(newYaw) * xzlen;
  84456. }
  84457. else {
  84458. newYaw = boneYaw - Math.PI * .75;
  84459. localTarget.z = Math.cos(newYaw) * xzlen;
  84460. localTarget.x = Math.sin(newYaw) * xzlen;
  84461. }
  84462. }
  84463. }
  84464. if (yaw != newYaw) {
  84465. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  84466. localTarget.addInPlace(bonePos);
  84467. target = localTarget;
  84468. }
  84469. }
  84470. }
  84471. var zaxis = BoneLookController._tmpVecs[5];
  84472. var xaxis = BoneLookController._tmpVecs[6];
  84473. var yaxis = BoneLookController._tmpVecs[7];
  84474. var _tmpQuat = BoneLookController._tmpQuat;
  84475. target.subtractToRef(bonePos, zaxis);
  84476. zaxis.normalize();
  84477. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  84478. xaxis.normalize();
  84479. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  84480. yaxis.normalize();
  84481. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  84482. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  84483. return;
  84484. }
  84485. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  84486. return;
  84487. }
  84488. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  84489. return;
  84490. }
  84491. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  84492. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  84493. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  84494. }
  84495. if (this.slerpAmount < 1) {
  84496. if (!this._slerping) {
  84497. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  84498. }
  84499. if (this._transformYawPitch) {
  84500. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  84501. }
  84502. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  84503. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  84504. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  84505. this._slerping = true;
  84506. }
  84507. else {
  84508. if (this._transformYawPitch) {
  84509. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  84510. }
  84511. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  84512. this._slerping = false;
  84513. }
  84514. };
  84515. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  84516. var angDiff = ang2 - ang1;
  84517. angDiff %= Math.PI * 2;
  84518. if (angDiff > Math.PI) {
  84519. angDiff -= Math.PI * 2;
  84520. }
  84521. else if (angDiff < -Math.PI) {
  84522. angDiff += Math.PI * 2;
  84523. }
  84524. return angDiff;
  84525. };
  84526. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  84527. ang1 %= (2 * Math.PI);
  84528. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  84529. ang2 %= (2 * Math.PI);
  84530. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  84531. var ab = 0;
  84532. if (ang1 < ang2) {
  84533. ab = ang2 - ang1;
  84534. }
  84535. else {
  84536. ab = ang1 - ang2;
  84537. }
  84538. if (ab > Math.PI) {
  84539. ab = Math.PI * 2 - ab;
  84540. }
  84541. return ab;
  84542. };
  84543. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  84544. ang %= (2 * Math.PI);
  84545. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  84546. ang1 %= (2 * Math.PI);
  84547. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  84548. ang2 %= (2 * Math.PI);
  84549. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  84550. if (ang1 < ang2) {
  84551. if (ang > ang1 && ang < ang2) {
  84552. return true;
  84553. }
  84554. }
  84555. else {
  84556. if (ang > ang2 && ang < ang1) {
  84557. return true;
  84558. }
  84559. }
  84560. return false;
  84561. };
  84562. 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()];
  84563. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  84564. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  84565. return BoneLookController;
  84566. }());
  84567. BABYLON.BoneLookController = BoneLookController;
  84568. })(BABYLON || (BABYLON = {}));
  84569. //# sourceMappingURL=babylon.boneLookController.js.map
  84570. var BABYLON;
  84571. (function (BABYLON) {
  84572. /**
  84573. * Class used to handle skinning animations
  84574. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  84575. */
  84576. var Skeleton = /** @class */ (function () {
  84577. /**
  84578. * Creates a new skeleton
  84579. * @param name defines the skeleton name
  84580. * @param id defines the skeleton Id
  84581. * @param scene defines the hosting scene
  84582. */
  84583. function Skeleton(
  84584. /** defines the skeleton name */
  84585. name,
  84586. /** defines the skeleton Id */
  84587. id, scene) {
  84588. this.name = name;
  84589. this.id = id;
  84590. /**
  84591. * Gets the list of child bones
  84592. */
  84593. this.bones = new Array();
  84594. /**
  84595. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  84596. */
  84597. this.needInitialSkinMatrix = false;
  84598. this._isDirty = true;
  84599. this._meshesWithPoseMatrix = new Array();
  84600. this._identity = BABYLON.Matrix.Identity();
  84601. this._ranges = {};
  84602. this._lastAbsoluteTransformsUpdateId = -1;
  84603. /**
  84604. * Specifies if the skeleton should be serialized
  84605. */
  84606. this.doNotSerialize = false;
  84607. this._animationPropertiesOverride = null;
  84608. // Events
  84609. /**
  84610. * An observable triggered before computing the skeleton's matrices
  84611. */
  84612. this.onBeforeComputeObservable = new BABYLON.Observable();
  84613. this.bones = [];
  84614. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84615. scene.skeletons.push(this);
  84616. //make sure it will recalculate the matrix next time prepare is called.
  84617. this._isDirty = true;
  84618. }
  84619. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  84620. /**
  84621. * Gets or sets the animation properties override
  84622. */
  84623. get: function () {
  84624. if (!this._animationPropertiesOverride) {
  84625. return this._scene.animationPropertiesOverride;
  84626. }
  84627. return this._animationPropertiesOverride;
  84628. },
  84629. set: function (value) {
  84630. this._animationPropertiesOverride = value;
  84631. },
  84632. enumerable: true,
  84633. configurable: true
  84634. });
  84635. // Members
  84636. /**
  84637. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  84638. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  84639. * @returns a Float32Array containing matrices data
  84640. */
  84641. Skeleton.prototype.getTransformMatrices = function (mesh) {
  84642. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  84643. return mesh._bonesTransformMatrices;
  84644. }
  84645. if (!this._transformMatrices) {
  84646. this.prepare();
  84647. }
  84648. return this._transformMatrices;
  84649. };
  84650. /**
  84651. * Gets the current hosting scene
  84652. * @returns a scene object
  84653. */
  84654. Skeleton.prototype.getScene = function () {
  84655. return this._scene;
  84656. };
  84657. // Methods
  84658. /**
  84659. * Gets a string representing the current skeleton data
  84660. * @param fullDetails defines a boolean indicating if we want a verbose version
  84661. * @returns a string representing the current skeleton data
  84662. */
  84663. Skeleton.prototype.toString = function (fullDetails) {
  84664. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  84665. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  84666. if (fullDetails) {
  84667. ret += ", Ranges: {";
  84668. var first = true;
  84669. for (var name_1 in this._ranges) {
  84670. if (first) {
  84671. ret += ", ";
  84672. first = false;
  84673. }
  84674. ret += name_1;
  84675. }
  84676. ret += "}";
  84677. }
  84678. return ret;
  84679. };
  84680. /**
  84681. * Get bone's index searching by name
  84682. * @param name defines bone's name to search for
  84683. * @return the indice of the bone. Returns -1 if not found
  84684. */
  84685. Skeleton.prototype.getBoneIndexByName = function (name) {
  84686. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  84687. if (this.bones[boneIndex].name === name) {
  84688. return boneIndex;
  84689. }
  84690. }
  84691. return -1;
  84692. };
  84693. /**
  84694. * Creater a new animation range
  84695. * @param name defines the name of the range
  84696. * @param from defines the start key
  84697. * @param to defines the end key
  84698. */
  84699. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  84700. // check name not already in use
  84701. if (!this._ranges[name]) {
  84702. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  84703. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  84704. if (this.bones[i].animations[0]) {
  84705. this.bones[i].animations[0].createRange(name, from, to);
  84706. }
  84707. }
  84708. }
  84709. };
  84710. /**
  84711. * Delete a specific animation range
  84712. * @param name defines the name of the range
  84713. * @param deleteFrames defines if frames must be removed as well
  84714. */
  84715. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  84716. if (deleteFrames === void 0) { deleteFrames = true; }
  84717. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  84718. if (this.bones[i].animations[0]) {
  84719. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  84720. }
  84721. }
  84722. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  84723. };
  84724. /**
  84725. * Gets a specific animation range
  84726. * @param name defines the name of the range to look for
  84727. * @returns the requested animation range or null if not found
  84728. */
  84729. Skeleton.prototype.getAnimationRange = function (name) {
  84730. return this._ranges[name];
  84731. };
  84732. /**
  84733. * Gets the list of all animation ranges defined on this skeleton
  84734. * @returns an array
  84735. */
  84736. Skeleton.prototype.getAnimationRanges = function () {
  84737. var animationRanges = [];
  84738. var name;
  84739. var i = 0;
  84740. for (name in this._ranges) {
  84741. animationRanges[i] = this._ranges[name];
  84742. i++;
  84743. }
  84744. return animationRanges;
  84745. };
  84746. /**
  84747. * Copy animation range from a source skeleton.
  84748. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  84749. * @param source defines the source skeleton
  84750. * @param name defines the name of the range to copy
  84751. * @param rescaleAsRequired defines if rescaling must be applied if required
  84752. * @returns true if operation was successful
  84753. */
  84754. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  84755. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  84756. if (this._ranges[name] || !source.getAnimationRange(name)) {
  84757. return false;
  84758. }
  84759. var ret = true;
  84760. var frameOffset = this._getHighestAnimationFrame() + 1;
  84761. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  84762. var boneDict = {};
  84763. var sourceBones = source.bones;
  84764. var nBones;
  84765. var i;
  84766. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  84767. boneDict[sourceBones[i].name] = sourceBones[i];
  84768. }
  84769. if (this.bones.length !== sourceBones.length) {
  84770. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  84771. ret = false;
  84772. }
  84773. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  84774. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  84775. var boneName = this.bones[i].name;
  84776. var sourceBone = boneDict[boneName];
  84777. if (sourceBone) {
  84778. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  84779. }
  84780. else {
  84781. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  84782. ret = false;
  84783. }
  84784. }
  84785. // do not call createAnimationRange(), since it also is done to bones, which was already done
  84786. var range = source.getAnimationRange(name);
  84787. if (range) {
  84788. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  84789. }
  84790. return ret;
  84791. };
  84792. /**
  84793. * Forces the skeleton to go to rest pose
  84794. */
  84795. Skeleton.prototype.returnToRest = function () {
  84796. for (var index = 0; index < this.bones.length; index++) {
  84797. this.bones[index].returnToRest();
  84798. }
  84799. };
  84800. Skeleton.prototype._getHighestAnimationFrame = function () {
  84801. var ret = 0;
  84802. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  84803. if (this.bones[i].animations[0]) {
  84804. var highest = this.bones[i].animations[0].getHighestFrame();
  84805. if (ret < highest) {
  84806. ret = highest;
  84807. }
  84808. }
  84809. }
  84810. return ret;
  84811. };
  84812. /**
  84813. * Begin a specific animation range
  84814. * @param name defines the name of the range to start
  84815. * @param loop defines if looping must be turned on (false by default)
  84816. * @param speedRatio defines the speed ratio to apply (1 by default)
  84817. * @param onAnimationEnd defines a callback which will be called when animation will end
  84818. * @returns a new animatable
  84819. */
  84820. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  84821. var range = this.getAnimationRange(name);
  84822. if (!range) {
  84823. return null;
  84824. }
  84825. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  84826. };
  84827. /** @hidden */
  84828. Skeleton.prototype._markAsDirty = function () {
  84829. this._isDirty = true;
  84830. };
  84831. /** @hidden */
  84832. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  84833. this._meshesWithPoseMatrix.push(mesh);
  84834. };
  84835. /** @hidden */
  84836. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  84837. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  84838. if (index > -1) {
  84839. this._meshesWithPoseMatrix.splice(index, 1);
  84840. }
  84841. };
  84842. /** @hidden */
  84843. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  84844. this.onBeforeComputeObservable.notifyObservers(this);
  84845. for (var index = 0; index < this.bones.length; index++) {
  84846. var bone = this.bones[index];
  84847. var parentBone = bone.getParent();
  84848. if (parentBone) {
  84849. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  84850. }
  84851. else {
  84852. if (initialSkinMatrix) {
  84853. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  84854. }
  84855. else {
  84856. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  84857. }
  84858. }
  84859. if (bone._index !== -1) {
  84860. var mappedIndex = bone._index === null ? index : bone._index;
  84861. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  84862. }
  84863. }
  84864. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  84865. };
  84866. /**
  84867. * Build all resources required to render a skeleton
  84868. */
  84869. Skeleton.prototype.prepare = function () {
  84870. if (!this._isDirty) {
  84871. return;
  84872. }
  84873. if (this.needInitialSkinMatrix) {
  84874. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  84875. var mesh = this._meshesWithPoseMatrix[index];
  84876. var poseMatrix = mesh.getPoseMatrix();
  84877. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  84878. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  84879. }
  84880. if (this._synchronizedWithMesh !== mesh) {
  84881. this._synchronizedWithMesh = mesh;
  84882. // Prepare bones
  84883. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  84884. var bone = this.bones[boneIndex];
  84885. if (!bone.getParent()) {
  84886. var matrix = bone.getBaseMatrix();
  84887. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  84888. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  84889. }
  84890. }
  84891. }
  84892. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  84893. }
  84894. }
  84895. else {
  84896. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  84897. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  84898. }
  84899. this._computeTransformMatrices(this._transformMatrices, null);
  84900. }
  84901. this._isDirty = false;
  84902. this._scene._activeBones.addCount(this.bones.length, false);
  84903. };
  84904. /**
  84905. * Gets the list of animatables currently running for this skeleton
  84906. * @returns an array of animatables
  84907. */
  84908. Skeleton.prototype.getAnimatables = function () {
  84909. if (!this._animatables || this._animatables.length !== this.bones.length) {
  84910. this._animatables = [];
  84911. for (var index = 0; index < this.bones.length; index++) {
  84912. this._animatables.push(this.bones[index]);
  84913. }
  84914. }
  84915. return this._animatables;
  84916. };
  84917. /**
  84918. * Clone the current skeleton
  84919. * @param name defines the name of the new skeleton
  84920. * @param id defines the id of the enw skeleton
  84921. * @returns the new skeleton
  84922. */
  84923. Skeleton.prototype.clone = function (name, id) {
  84924. var result = new Skeleton(name, id || name, this._scene);
  84925. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  84926. for (var index = 0; index < this.bones.length; index++) {
  84927. var source = this.bones[index];
  84928. var parentBone = null;
  84929. var parent_1 = source.getParent();
  84930. if (parent_1) {
  84931. var parentIndex = this.bones.indexOf(parent_1);
  84932. parentBone = result.bones[parentIndex];
  84933. }
  84934. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  84935. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  84936. }
  84937. if (this._ranges) {
  84938. result._ranges = {};
  84939. for (var rangeName in this._ranges) {
  84940. var range = this._ranges[rangeName];
  84941. if (range) {
  84942. result._ranges[rangeName] = range.clone();
  84943. }
  84944. }
  84945. }
  84946. this._isDirty = true;
  84947. return result;
  84948. };
  84949. /**
  84950. * Enable animation blending for this skeleton
  84951. * @param blendingSpeed defines the blending speed to apply
  84952. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  84953. */
  84954. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  84955. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  84956. this.bones.forEach(function (bone) {
  84957. bone.animations.forEach(function (animation) {
  84958. animation.enableBlending = true;
  84959. animation.blendingSpeed = blendingSpeed;
  84960. });
  84961. });
  84962. };
  84963. /**
  84964. * Releases all resources associated with the current skeleton
  84965. */
  84966. Skeleton.prototype.dispose = function () {
  84967. this._meshesWithPoseMatrix = [];
  84968. // Animations
  84969. this.getScene().stopAnimation(this);
  84970. // Remove from scene
  84971. this.getScene().removeSkeleton(this);
  84972. };
  84973. /**
  84974. * Serialize the skeleton in a JSON object
  84975. * @returns a JSON object
  84976. */
  84977. Skeleton.prototype.serialize = function () {
  84978. var serializationObject = {};
  84979. serializationObject.name = this.name;
  84980. serializationObject.id = this.id;
  84981. if (this.dimensionsAtRest) {
  84982. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  84983. }
  84984. serializationObject.bones = [];
  84985. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  84986. for (var index = 0; index < this.bones.length; index++) {
  84987. var bone = this.bones[index];
  84988. var parent_2 = bone.getParent();
  84989. var serializedBone = {
  84990. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  84991. name: bone.name,
  84992. matrix: bone.getBaseMatrix().toArray(),
  84993. rest: bone.getRestPose().toArray()
  84994. };
  84995. serializationObject.bones.push(serializedBone);
  84996. if (bone.length) {
  84997. serializedBone.length = bone.length;
  84998. }
  84999. if (bone.metadata) {
  85000. serializedBone.metadata = bone.metadata;
  85001. }
  85002. if (bone.animations && bone.animations.length > 0) {
  85003. serializedBone.animation = bone.animations[0].serialize();
  85004. }
  85005. serializationObject.ranges = [];
  85006. for (var name in this._ranges) {
  85007. var source = this._ranges[name];
  85008. if (!source) {
  85009. continue;
  85010. }
  85011. var range = {};
  85012. range.name = name;
  85013. range.from = source.from;
  85014. range.to = source.to;
  85015. serializationObject.ranges.push(range);
  85016. }
  85017. }
  85018. return serializationObject;
  85019. };
  85020. /**
  85021. * Creates a new skeleton from serialized data
  85022. * @param parsedSkeleton defines the serialized data
  85023. * @param scene defines the hosting scene
  85024. * @returns a new skeleton
  85025. */
  85026. Skeleton.Parse = function (parsedSkeleton, scene) {
  85027. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  85028. if (parsedSkeleton.dimensionsAtRest) {
  85029. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  85030. }
  85031. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  85032. var index;
  85033. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  85034. var parsedBone = parsedSkeleton.bones[index];
  85035. var parentBone = null;
  85036. if (parsedBone.parentBoneIndex > -1) {
  85037. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  85038. }
  85039. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  85040. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  85041. if (parsedBone.length) {
  85042. bone.length = parsedBone.length;
  85043. }
  85044. if (parsedBone.metadata) {
  85045. bone.metadata = parsedBone.metadata;
  85046. }
  85047. if (parsedBone.animation) {
  85048. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  85049. }
  85050. }
  85051. // placed after bones, so createAnimationRange can cascade down
  85052. if (parsedSkeleton.ranges) {
  85053. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  85054. var data = parsedSkeleton.ranges[index];
  85055. skeleton.createAnimationRange(data.name, data.from, data.to);
  85056. }
  85057. }
  85058. return skeleton;
  85059. };
  85060. /**
  85061. * Compute all node absolute transforms
  85062. * @param forceUpdate defines if computation must be done even if cache is up to date
  85063. */
  85064. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  85065. if (forceUpdate === void 0) { forceUpdate = false; }
  85066. var renderId = this._scene.getRenderId();
  85067. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  85068. this.bones[0].computeAbsoluteTransforms();
  85069. this._lastAbsoluteTransformsUpdateId = renderId;
  85070. }
  85071. };
  85072. /**
  85073. * Gets the root pose matrix
  85074. * @returns a matrix
  85075. */
  85076. Skeleton.prototype.getPoseMatrix = function () {
  85077. var poseMatrix = null;
  85078. if (this._meshesWithPoseMatrix.length > 0) {
  85079. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  85080. }
  85081. return poseMatrix;
  85082. };
  85083. /**
  85084. * Sorts bones per internal index
  85085. */
  85086. Skeleton.prototype.sortBones = function () {
  85087. var bones = new Array();
  85088. var visited = new Array(this.bones.length);
  85089. for (var index = 0; index < this.bones.length; index++) {
  85090. this._sortBones(index, bones, visited);
  85091. }
  85092. this.bones = bones;
  85093. };
  85094. Skeleton.prototype._sortBones = function (index, bones, visited) {
  85095. if (visited[index]) {
  85096. return;
  85097. }
  85098. visited[index] = true;
  85099. var bone = this.bones[index];
  85100. if (bone._index === undefined) {
  85101. bone._index = index;
  85102. }
  85103. var parentBone = bone.getParent();
  85104. if (parentBone) {
  85105. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  85106. }
  85107. bones.push(bone);
  85108. };
  85109. return Skeleton;
  85110. }());
  85111. BABYLON.Skeleton = Skeleton;
  85112. })(BABYLON || (BABYLON = {}));
  85113. //# sourceMappingURL=babylon.skeleton.js.map
  85114. var BABYLON;
  85115. (function (BABYLON) {
  85116. ;
  85117. /**
  85118. * This groups tools to convert HDR texture to native colors array.
  85119. */
  85120. var HDRTools = /** @class */ (function () {
  85121. function HDRTools() {
  85122. }
  85123. HDRTools.Ldexp = function (mantissa, exponent) {
  85124. if (exponent > 1023) {
  85125. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  85126. }
  85127. if (exponent < -1074) {
  85128. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  85129. }
  85130. return mantissa * Math.pow(2, exponent);
  85131. };
  85132. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  85133. if (exponent > 0) { /*nonzero pixel*/
  85134. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  85135. float32array[index + 0] = red * exponent;
  85136. float32array[index + 1] = green * exponent;
  85137. float32array[index + 2] = blue * exponent;
  85138. }
  85139. else {
  85140. float32array[index + 0] = 0;
  85141. float32array[index + 1] = 0;
  85142. float32array[index + 2] = 0;
  85143. }
  85144. };
  85145. HDRTools.readStringLine = function (uint8array, startIndex) {
  85146. var line = "";
  85147. var character = "";
  85148. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  85149. character = String.fromCharCode(uint8array[i]);
  85150. if (character == "\n") {
  85151. break;
  85152. }
  85153. line += character;
  85154. }
  85155. return line;
  85156. };
  85157. /**
  85158. * Reads header information from an RGBE texture stored in a native array.
  85159. * More information on this format are available here:
  85160. * https://en.wikipedia.org/wiki/RGBE_image_format
  85161. *
  85162. * @param uint8array The binary file stored in native array.
  85163. * @return The header information.
  85164. */
  85165. HDRTools.RGBE_ReadHeader = function (uint8array) {
  85166. var height = 0;
  85167. var width = 0;
  85168. var line = this.readStringLine(uint8array, 0);
  85169. if (line[0] != '#' || line[1] != '?') {
  85170. throw "Bad HDR Format.";
  85171. }
  85172. var endOfHeader = false;
  85173. var findFormat = false;
  85174. var lineIndex = 0;
  85175. do {
  85176. lineIndex += (line.length + 1);
  85177. line = this.readStringLine(uint8array, lineIndex);
  85178. if (line == "FORMAT=32-bit_rle_rgbe") {
  85179. findFormat = true;
  85180. }
  85181. else if (line.length == 0) {
  85182. endOfHeader = true;
  85183. }
  85184. } while (!endOfHeader);
  85185. if (!findFormat) {
  85186. throw "HDR Bad header format, unsupported FORMAT";
  85187. }
  85188. lineIndex += (line.length + 1);
  85189. line = this.readStringLine(uint8array, lineIndex);
  85190. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  85191. var match = sizeRegexp.exec(line);
  85192. // TODO. Support +Y and -X if needed.
  85193. if (!match || match.length < 3) {
  85194. throw "HDR Bad header format, no size";
  85195. }
  85196. width = parseInt(match[2]);
  85197. height = parseInt(match[1]);
  85198. if (width < 8 || width > 0x7fff) {
  85199. throw "HDR Bad header format, unsupported size";
  85200. }
  85201. lineIndex += (line.length + 1);
  85202. return {
  85203. height: height,
  85204. width: width,
  85205. dataPosition: lineIndex
  85206. };
  85207. };
  85208. /**
  85209. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  85210. * This RGBE texture needs to store the information as a panorama.
  85211. *
  85212. * More information on this format are available here:
  85213. * https://en.wikipedia.org/wiki/RGBE_image_format
  85214. *
  85215. * @param buffer The binary file stored in an array buffer.
  85216. * @param size The expected size of the extracted cubemap.
  85217. * @return The Cube Map information.
  85218. */
  85219. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  85220. var uint8array = new Uint8Array(buffer);
  85221. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  85222. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  85223. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  85224. return cubeMapData;
  85225. };
  85226. /**
  85227. * Returns the pixels data extracted from an RGBE texture.
  85228. * This pixels will be stored left to right up to down in the R G B order in one array.
  85229. *
  85230. * More information on this format are available here:
  85231. * https://en.wikipedia.org/wiki/RGBE_image_format
  85232. *
  85233. * @param uint8array The binary file stored in an array buffer.
  85234. * @param hdrInfo The header information of the file.
  85235. * @return The pixels data in RGB right to left up to down order.
  85236. */
  85237. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  85238. // Keep for multi format supports.
  85239. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  85240. };
  85241. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  85242. var num_scanlines = hdrInfo.height;
  85243. var scanline_width = hdrInfo.width;
  85244. var a, b, c, d, count;
  85245. var dataIndex = hdrInfo.dataPosition;
  85246. var index = 0, endIndex = 0, i = 0;
  85247. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  85248. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  85249. // 3 channels of 4 bytes per pixel in float.
  85250. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  85251. var resultArray = new Float32Array(resultBuffer);
  85252. // read in each successive scanline
  85253. while (num_scanlines > 0) {
  85254. a = uint8array[dataIndex++];
  85255. b = uint8array[dataIndex++];
  85256. c = uint8array[dataIndex++];
  85257. d = uint8array[dataIndex++];
  85258. if (a != 2 || b != 2 || (c & 0x80)) {
  85259. // this file is not run length encoded
  85260. throw "HDR Bad header format, not RLE";
  85261. }
  85262. if (((c << 8) | d) != scanline_width) {
  85263. throw "HDR Bad header format, wrong scan line width";
  85264. }
  85265. index = 0;
  85266. // read each of the four channels for the scanline into the buffer
  85267. for (i = 0; i < 4; i++) {
  85268. endIndex = (i + 1) * scanline_width;
  85269. while (index < endIndex) {
  85270. a = uint8array[dataIndex++];
  85271. b = uint8array[dataIndex++];
  85272. if (a > 128) {
  85273. // a run of the same value
  85274. count = a - 128;
  85275. if ((count == 0) || (count > endIndex - index)) {
  85276. throw "HDR Bad Format, bad scanline data (run)";
  85277. }
  85278. while (count-- > 0) {
  85279. scanLineArray[index++] = b;
  85280. }
  85281. }
  85282. else {
  85283. // a non-run
  85284. count = a;
  85285. if ((count == 0) || (count > endIndex - index)) {
  85286. throw "HDR Bad Format, bad scanline data (non-run)";
  85287. }
  85288. scanLineArray[index++] = b;
  85289. if (--count > 0) {
  85290. for (var j = 0; j < count; j++) {
  85291. scanLineArray[index++] = uint8array[dataIndex++];
  85292. }
  85293. }
  85294. }
  85295. }
  85296. }
  85297. // now convert data from buffer into floats
  85298. for (i = 0; i < scanline_width; i++) {
  85299. a = scanLineArray[i];
  85300. b = scanLineArray[i + scanline_width];
  85301. c = scanLineArray[i + 2 * scanline_width];
  85302. d = scanLineArray[i + 3 * scanline_width];
  85303. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  85304. }
  85305. num_scanlines--;
  85306. }
  85307. return resultArray;
  85308. };
  85309. return HDRTools;
  85310. }());
  85311. BABYLON.HDRTools = HDRTools;
  85312. })(BABYLON || (BABYLON = {}));
  85313. //# sourceMappingURL=babylon.hdr.js.map
  85314. var BABYLON;
  85315. (function (BABYLON) {
  85316. /**
  85317. * This represents a texture coming from an HDR input.
  85318. *
  85319. * The only supported format is currently panorama picture stored in RGBE format.
  85320. * Example of such files can be found on HDRLib: http://hdrlib.com/
  85321. */
  85322. var HDRCubeTexture = /** @class */ (function (_super) {
  85323. __extends(HDRCubeTexture, _super);
  85324. /**
  85325. * Instantiates an HDRTexture from the following parameters.
  85326. *
  85327. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  85328. * @param scene The scene the texture will be used in
  85329. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  85330. * @param noMipmap Forces to not generate the mipmap if true
  85331. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  85332. * @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)
  85333. * @param reserved Reserved flag for internal use.
  85334. */
  85335. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  85336. if (noMipmap === void 0) { noMipmap = false; }
  85337. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85338. if (gammaSpace === void 0) { gammaSpace = false; }
  85339. if (reserved === void 0) { reserved = false; }
  85340. if (onLoad === void 0) { onLoad = null; }
  85341. if (onError === void 0) { onError = null; }
  85342. var _this = _super.call(this, scene) || this;
  85343. _this._generateHarmonics = true;
  85344. _this._onLoad = null;
  85345. _this._onError = null;
  85346. /**
  85347. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  85348. */
  85349. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  85350. _this._isBlocking = true;
  85351. _this._rotationY = 0;
  85352. /**
  85353. * Gets or sets the center of the bounding box associated with the cube texture
  85354. * It must define where the camera used to render the texture was set
  85355. */
  85356. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  85357. if (!url) {
  85358. return _this;
  85359. }
  85360. _this.name = url;
  85361. _this.url = url;
  85362. _this.hasAlpha = false;
  85363. _this.isCube = true;
  85364. _this._textureMatrix = BABYLON.Matrix.Identity();
  85365. _this._onLoad = onLoad;
  85366. _this._onError = onError;
  85367. _this.gammaSpace = gammaSpace;
  85368. _this._noMipmap = noMipmap;
  85369. _this._size = size;
  85370. _this._texture = _this._getFromCache(url, _this._noMipmap);
  85371. if (!_this._texture) {
  85372. if (!scene.useDelayedTextureLoading) {
  85373. _this.loadTexture();
  85374. }
  85375. else {
  85376. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  85377. }
  85378. }
  85379. return _this;
  85380. }
  85381. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  85382. /**
  85383. * Gets wether or not the texture is blocking during loading.
  85384. */
  85385. get: function () {
  85386. return this._isBlocking;
  85387. },
  85388. /**
  85389. * Sets wether or not the texture is blocking during loading.
  85390. */
  85391. set: function (value) {
  85392. this._isBlocking = value;
  85393. },
  85394. enumerable: true,
  85395. configurable: true
  85396. });
  85397. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  85398. /**
  85399. * Gets texture matrix rotation angle around Y axis radians.
  85400. */
  85401. get: function () {
  85402. return this._rotationY;
  85403. },
  85404. /**
  85405. * Sets texture matrix rotation angle around Y axis in radians.
  85406. */
  85407. set: function (value) {
  85408. this._rotationY = value;
  85409. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  85410. },
  85411. enumerable: true,
  85412. configurable: true
  85413. });
  85414. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  85415. get: function () {
  85416. return this._boundingBoxSize;
  85417. },
  85418. /**
  85419. * Gets or sets the size of the bounding box associated with the cube texture
  85420. * When defined, the cubemap will switch to local mode
  85421. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  85422. * @example https://www.babylonjs-playground.com/#RNASML
  85423. */
  85424. set: function (value) {
  85425. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  85426. return;
  85427. }
  85428. this._boundingBoxSize = value;
  85429. var scene = this.getScene();
  85430. if (scene) {
  85431. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  85432. }
  85433. },
  85434. enumerable: true,
  85435. configurable: true
  85436. });
  85437. /**
  85438. * Occurs when the file is raw .hdr file.
  85439. */
  85440. HDRCubeTexture.prototype.loadTexture = function () {
  85441. var _this = this;
  85442. var callback = function (buffer) {
  85443. _this.lodGenerationOffset = 0.0;
  85444. _this.lodGenerationScale = 0.8;
  85445. var scene = _this.getScene();
  85446. if (!scene) {
  85447. return null;
  85448. }
  85449. // Extract the raw linear data.
  85450. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  85451. // Generate harmonics if needed.
  85452. if (_this._generateHarmonics) {
  85453. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  85454. _this.sphericalPolynomial = sphericalPolynomial;
  85455. }
  85456. var results = [];
  85457. var byteArray = null;
  85458. // Push each faces.
  85459. for (var j = 0; j < 6; j++) {
  85460. // Create uintarray fallback.
  85461. if (!scene.getEngine().getCaps().textureFloat) {
  85462. // 3 channels of 1 bytes per pixel in bytes.
  85463. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  85464. byteArray = new Uint8Array(byteBuffer);
  85465. }
  85466. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  85467. // If special cases.
  85468. if (_this.gammaSpace || byteArray) {
  85469. for (var i = 0; i < _this._size * _this._size; i++) {
  85470. // Put in gamma space if requested.
  85471. if (_this.gammaSpace) {
  85472. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  85473. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  85474. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  85475. }
  85476. // Convert to int texture for fallback.
  85477. if (byteArray) {
  85478. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  85479. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  85480. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  85481. // May use luminance instead if the result is not accurate.
  85482. var max = Math.max(Math.max(r, g), b);
  85483. if (max > 255) {
  85484. var scale = 255 / max;
  85485. r *= scale;
  85486. g *= scale;
  85487. b *= scale;
  85488. }
  85489. byteArray[(i * 3) + 0] = r;
  85490. byteArray[(i * 3) + 1] = g;
  85491. byteArray[(i * 3) + 2] = b;
  85492. }
  85493. }
  85494. }
  85495. if (byteArray) {
  85496. results.push(byteArray);
  85497. }
  85498. else {
  85499. results.push(dataFace);
  85500. }
  85501. }
  85502. return results;
  85503. };
  85504. var scene = this.getScene();
  85505. if (scene) {
  85506. 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);
  85507. }
  85508. };
  85509. HDRCubeTexture.prototype.clone = function () {
  85510. var scene = this.getScene();
  85511. if (!scene) {
  85512. return this;
  85513. }
  85514. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  85515. // Base texture
  85516. newTexture.level = this.level;
  85517. newTexture.wrapU = this.wrapU;
  85518. newTexture.wrapV = this.wrapV;
  85519. newTexture.coordinatesIndex = this.coordinatesIndex;
  85520. newTexture.coordinatesMode = this.coordinatesMode;
  85521. return newTexture;
  85522. };
  85523. // Methods
  85524. HDRCubeTexture.prototype.delayLoad = function () {
  85525. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  85526. return;
  85527. }
  85528. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  85529. this._texture = this._getFromCache(this.url, this._noMipmap);
  85530. if (!this._texture) {
  85531. this.loadTexture();
  85532. }
  85533. };
  85534. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  85535. return this._textureMatrix;
  85536. };
  85537. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  85538. this._textureMatrix = value;
  85539. };
  85540. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  85541. var texture = null;
  85542. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  85543. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  85544. texture.name = parsedTexture.name;
  85545. texture.hasAlpha = parsedTexture.hasAlpha;
  85546. texture.level = parsedTexture.level;
  85547. texture.coordinatesMode = parsedTexture.coordinatesMode;
  85548. texture.isBlocking = parsedTexture.isBlocking;
  85549. }
  85550. if (texture) {
  85551. if (parsedTexture.boundingBoxPosition) {
  85552. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  85553. }
  85554. if (parsedTexture.boundingBoxSize) {
  85555. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  85556. }
  85557. if (parsedTexture.rotationY) {
  85558. texture.rotationY = parsedTexture.rotationY;
  85559. }
  85560. }
  85561. return texture;
  85562. };
  85563. HDRCubeTexture.prototype.serialize = function () {
  85564. if (!this.name) {
  85565. return null;
  85566. }
  85567. var serializationObject = {};
  85568. serializationObject.name = this.name;
  85569. serializationObject.hasAlpha = this.hasAlpha;
  85570. serializationObject.isCube = true;
  85571. serializationObject.level = this.level;
  85572. serializationObject.size = this._size;
  85573. serializationObject.coordinatesMode = this.coordinatesMode;
  85574. serializationObject.useInGammaSpace = this.gammaSpace;
  85575. serializationObject.generateHarmonics = this._generateHarmonics;
  85576. serializationObject.customType = "BABYLON.HDRCubeTexture";
  85577. serializationObject.noMipmap = this._noMipmap;
  85578. serializationObject.isBlocking = this._isBlocking;
  85579. serializationObject.rotationY = this._rotationY;
  85580. return serializationObject;
  85581. };
  85582. HDRCubeTexture._facesMapping = [
  85583. "right",
  85584. "left",
  85585. "up",
  85586. "down",
  85587. "front",
  85588. "back"
  85589. ];
  85590. return HDRCubeTexture;
  85591. }(BABYLON.BaseTexture));
  85592. BABYLON.HDRCubeTexture = HDRCubeTexture;
  85593. })(BABYLON || (BABYLON = {}));
  85594. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  85595. var BABYLON;
  85596. (function (BABYLON) {
  85597. /**
  85598. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  85599. */
  85600. var PanoramaToCubeMapTools = /** @class */ (function () {
  85601. function PanoramaToCubeMapTools() {
  85602. }
  85603. /**
  85604. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  85605. *
  85606. * @param float32Array The source data.
  85607. * @param inputWidth The width of the input panorama.
  85608. * @param inputhHeight The height of the input panorama.
  85609. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  85610. * @return The cubemap data
  85611. */
  85612. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  85613. if (!float32Array) {
  85614. throw "ConvertPanoramaToCubemap: input cannot be null";
  85615. }
  85616. if (float32Array.length != inputWidth * inputHeight * 3) {
  85617. throw "ConvertPanoramaToCubemap: input size is wrong";
  85618. }
  85619. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  85620. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  85621. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  85622. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  85623. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  85624. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  85625. return {
  85626. front: textureFront,
  85627. back: textureBack,
  85628. left: textureLeft,
  85629. right: textureRight,
  85630. up: textureUp,
  85631. down: textureDown,
  85632. size: size,
  85633. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  85634. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  85635. gammaSpace: false,
  85636. };
  85637. };
  85638. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  85639. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  85640. var textureArray = new Float32Array(buffer);
  85641. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  85642. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  85643. var dy = 1 / texSize;
  85644. var fy = 0;
  85645. for (var y = 0; y < texSize; y++) {
  85646. var xv1 = faceData[0];
  85647. var xv2 = faceData[2];
  85648. for (var x = 0; x < texSize; x++) {
  85649. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  85650. v.normalize();
  85651. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  85652. // 3 channels per pixels
  85653. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  85654. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  85655. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  85656. xv1 = xv1.add(rotDX1);
  85657. xv2 = xv2.add(rotDX2);
  85658. }
  85659. fy += dy;
  85660. }
  85661. return textureArray;
  85662. };
  85663. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  85664. var theta = Math.atan2(vDir.z, vDir.x);
  85665. var phi = Math.acos(vDir.y);
  85666. while (theta < -Math.PI)
  85667. theta += 2 * Math.PI;
  85668. while (theta > Math.PI)
  85669. theta -= 2 * Math.PI;
  85670. var dx = theta / Math.PI;
  85671. var dy = phi / Math.PI;
  85672. // recenter.
  85673. dx = dx * 0.5 + 0.5;
  85674. var px = Math.round(dx * inputWidth);
  85675. if (px < 0)
  85676. px = 0;
  85677. else if (px >= inputWidth)
  85678. px = inputWidth - 1;
  85679. var py = Math.round(dy * inputHeight);
  85680. if (py < 0)
  85681. py = 0;
  85682. else if (py >= inputHeight)
  85683. py = inputHeight - 1;
  85684. var inputY = (inputHeight - py - 1);
  85685. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  85686. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  85687. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  85688. return {
  85689. r: r,
  85690. g: g,
  85691. b: b
  85692. };
  85693. };
  85694. PanoramaToCubeMapTools.FACE_FRONT = [
  85695. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  85696. new BABYLON.Vector3(1.0, -1.0, -1.0),
  85697. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  85698. new BABYLON.Vector3(1.0, 1.0, -1.0)
  85699. ];
  85700. PanoramaToCubeMapTools.FACE_BACK = [
  85701. new BABYLON.Vector3(1.0, -1.0, 1.0),
  85702. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  85703. new BABYLON.Vector3(1.0, 1.0, 1.0),
  85704. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  85705. ];
  85706. PanoramaToCubeMapTools.FACE_RIGHT = [
  85707. new BABYLON.Vector3(1.0, -1.0, -1.0),
  85708. new BABYLON.Vector3(1.0, -1.0, 1.0),
  85709. new BABYLON.Vector3(1.0, 1.0, -1.0),
  85710. new BABYLON.Vector3(1.0, 1.0, 1.0)
  85711. ];
  85712. PanoramaToCubeMapTools.FACE_LEFT = [
  85713. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  85714. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  85715. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  85716. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  85717. ];
  85718. PanoramaToCubeMapTools.FACE_DOWN = [
  85719. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  85720. new BABYLON.Vector3(1.0, 1.0, -1.0),
  85721. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  85722. new BABYLON.Vector3(1.0, 1.0, 1.0)
  85723. ];
  85724. PanoramaToCubeMapTools.FACE_UP = [
  85725. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  85726. new BABYLON.Vector3(1.0, -1.0, 1.0),
  85727. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  85728. new BABYLON.Vector3(1.0, -1.0, -1.0)
  85729. ];
  85730. return PanoramaToCubeMapTools;
  85731. }());
  85732. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  85733. })(BABYLON || (BABYLON = {}));
  85734. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  85735. var BABYLON;
  85736. (function (BABYLON) {
  85737. var IndexedVector2 = /** @class */ (function (_super) {
  85738. __extends(IndexedVector2, _super);
  85739. function IndexedVector2(original, index) {
  85740. var _this = _super.call(this, original.x, original.y) || this;
  85741. _this.index = index;
  85742. return _this;
  85743. }
  85744. return IndexedVector2;
  85745. }(BABYLON.Vector2));
  85746. var PolygonPoints = /** @class */ (function () {
  85747. function PolygonPoints() {
  85748. this.elements = new Array();
  85749. }
  85750. PolygonPoints.prototype.add = function (originalPoints) {
  85751. var _this = this;
  85752. var result = new Array();
  85753. originalPoints.forEach(function (point) {
  85754. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  85755. var newPoint = new IndexedVector2(point, _this.elements.length);
  85756. result.push(newPoint);
  85757. _this.elements.push(newPoint);
  85758. }
  85759. });
  85760. return result;
  85761. };
  85762. PolygonPoints.prototype.computeBounds = function () {
  85763. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  85764. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  85765. this.elements.forEach(function (point) {
  85766. // x
  85767. if (point.x < lmin.x) {
  85768. lmin.x = point.x;
  85769. }
  85770. else if (point.x > lmax.x) {
  85771. lmax.x = point.x;
  85772. }
  85773. // y
  85774. if (point.y < lmin.y) {
  85775. lmin.y = point.y;
  85776. }
  85777. else if (point.y > lmax.y) {
  85778. lmax.y = point.y;
  85779. }
  85780. });
  85781. return {
  85782. min: lmin,
  85783. max: lmax,
  85784. width: lmax.x - lmin.x,
  85785. height: lmax.y - lmin.y
  85786. };
  85787. };
  85788. return PolygonPoints;
  85789. }());
  85790. var Polygon = /** @class */ (function () {
  85791. function Polygon() {
  85792. }
  85793. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  85794. return [
  85795. new BABYLON.Vector2(xmin, ymin),
  85796. new BABYLON.Vector2(xmax, ymin),
  85797. new BABYLON.Vector2(xmax, ymax),
  85798. new BABYLON.Vector2(xmin, ymax)
  85799. ];
  85800. };
  85801. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  85802. if (cx === void 0) { cx = 0; }
  85803. if (cy === void 0) { cy = 0; }
  85804. if (numberOfSides === void 0) { numberOfSides = 32; }
  85805. var result = new Array();
  85806. var angle = 0;
  85807. var increment = (Math.PI * 2) / numberOfSides;
  85808. for (var i = 0; i < numberOfSides; i++) {
  85809. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  85810. angle -= increment;
  85811. }
  85812. return result;
  85813. };
  85814. Polygon.Parse = function (input) {
  85815. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  85816. var i, result = [];
  85817. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  85818. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  85819. }
  85820. return result;
  85821. };
  85822. Polygon.StartingAt = function (x, y) {
  85823. return BABYLON.Path2.StartingAt(x, y);
  85824. };
  85825. return Polygon;
  85826. }());
  85827. BABYLON.Polygon = Polygon;
  85828. var PolygonMeshBuilder = /** @class */ (function () {
  85829. function PolygonMeshBuilder(name, contours, scene) {
  85830. this._points = new PolygonPoints();
  85831. this._outlinepoints = new PolygonPoints();
  85832. this._holes = new Array();
  85833. this._epoints = new Array();
  85834. this._eholes = new Array();
  85835. this._name = name;
  85836. this._scene = scene;
  85837. var points;
  85838. if (contours instanceof BABYLON.Path2) {
  85839. points = contours.getPoints();
  85840. }
  85841. else {
  85842. points = contours;
  85843. }
  85844. this._addToepoint(points);
  85845. this._points.add(points);
  85846. this._outlinepoints.add(points);
  85847. if (typeof earcut === 'undefined') {
  85848. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  85849. }
  85850. }
  85851. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  85852. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  85853. var p = points_1[_i];
  85854. this._epoints.push(p.x, p.y);
  85855. }
  85856. };
  85857. PolygonMeshBuilder.prototype.addHole = function (hole) {
  85858. this._points.add(hole);
  85859. var holepoints = new PolygonPoints();
  85860. holepoints.add(hole);
  85861. this._holes.push(holepoints);
  85862. this._eholes.push(this._epoints.length / 2);
  85863. this._addToepoint(hole);
  85864. return this;
  85865. };
  85866. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  85867. var _this = this;
  85868. if (updatable === void 0) { updatable = false; }
  85869. if (depth === void 0) { depth = 0; }
  85870. var result = new BABYLON.Mesh(this._name, this._scene);
  85871. var normals = new Array();
  85872. var positions = new Array();
  85873. var uvs = new Array();
  85874. var bounds = this._points.computeBounds();
  85875. this._points.elements.forEach(function (p) {
  85876. normals.push(0, 1.0, 0);
  85877. positions.push(p.x, 0, p.y);
  85878. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  85879. });
  85880. var indices = new Array();
  85881. var res = earcut(this._epoints, this._eholes, 2);
  85882. for (var i = 0; i < res.length; i++) {
  85883. indices.push(res[i]);
  85884. }
  85885. if (depth > 0) {
  85886. var positionscount = (positions.length / 3); //get the current pointcount
  85887. this._points.elements.forEach(function (p) {
  85888. normals.push(0, -1.0, 0);
  85889. positions.push(p.x, -depth, p.y);
  85890. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  85891. });
  85892. var totalCount = indices.length;
  85893. for (var i = 0; i < totalCount; i += 3) {
  85894. var i0 = indices[i + 0];
  85895. var i1 = indices[i + 1];
  85896. var i2 = indices[i + 2];
  85897. indices.push(i2 + positionscount);
  85898. indices.push(i1 + positionscount);
  85899. indices.push(i0 + positionscount);
  85900. }
  85901. //Add the sides
  85902. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  85903. this._holes.forEach(function (hole) {
  85904. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  85905. });
  85906. }
  85907. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  85908. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  85909. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  85910. result.setIndices(indices);
  85911. return result;
  85912. };
  85913. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  85914. var StartIndex = positions.length / 3;
  85915. var ulength = 0;
  85916. for (var i = 0; i < points.elements.length; i++) {
  85917. var p = points.elements[i];
  85918. var p1;
  85919. if ((i + 1) > points.elements.length - 1) {
  85920. p1 = points.elements[0];
  85921. }
  85922. else {
  85923. p1 = points.elements[i + 1];
  85924. }
  85925. positions.push(p.x, 0, p.y);
  85926. positions.push(p.x, -depth, p.y);
  85927. positions.push(p1.x, 0, p1.y);
  85928. positions.push(p1.x, -depth, p1.y);
  85929. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  85930. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  85931. var v3 = v2.subtract(v1);
  85932. var v4 = new BABYLON.Vector3(0, 1, 0);
  85933. var vn = BABYLON.Vector3.Cross(v3, v4);
  85934. vn = vn.normalize();
  85935. uvs.push(ulength / bounds.width, 0);
  85936. uvs.push(ulength / bounds.width, 1);
  85937. ulength += v3.length();
  85938. uvs.push((ulength / bounds.width), 0);
  85939. uvs.push((ulength / bounds.width), 1);
  85940. if (!flip) {
  85941. normals.push(-vn.x, -vn.y, -vn.z);
  85942. normals.push(-vn.x, -vn.y, -vn.z);
  85943. normals.push(-vn.x, -vn.y, -vn.z);
  85944. normals.push(-vn.x, -vn.y, -vn.z);
  85945. indices.push(StartIndex);
  85946. indices.push(StartIndex + 1);
  85947. indices.push(StartIndex + 2);
  85948. indices.push(StartIndex + 1);
  85949. indices.push(StartIndex + 3);
  85950. indices.push(StartIndex + 2);
  85951. }
  85952. else {
  85953. normals.push(vn.x, vn.y, vn.z);
  85954. normals.push(vn.x, vn.y, vn.z);
  85955. normals.push(vn.x, vn.y, vn.z);
  85956. normals.push(vn.x, vn.y, vn.z);
  85957. indices.push(StartIndex);
  85958. indices.push(StartIndex + 2);
  85959. indices.push(StartIndex + 1);
  85960. indices.push(StartIndex + 1);
  85961. indices.push(StartIndex + 2);
  85962. indices.push(StartIndex + 3);
  85963. }
  85964. StartIndex += 4;
  85965. }
  85966. ;
  85967. };
  85968. return PolygonMeshBuilder;
  85969. }());
  85970. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  85971. })(BABYLON || (BABYLON = {}));
  85972. //# sourceMappingURL=babylon.polygonMesh.js.map
  85973. var BABYLON;
  85974. (function (BABYLON) {
  85975. // Unique ID when we import meshes from Babylon to CSG
  85976. var currentCSGMeshId = 0;
  85977. // # class Vertex
  85978. // Represents a vertex of a polygon. Use your own vertex class instead of this
  85979. // one to provide additional features like texture coordinates and vertex
  85980. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  85981. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  85982. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  85983. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  85984. // is not used anywhere else.
  85985. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  85986. var Vertex = /** @class */ (function () {
  85987. function Vertex(pos, normal, uv) {
  85988. this.pos = pos;
  85989. this.normal = normal;
  85990. this.uv = uv;
  85991. }
  85992. Vertex.prototype.clone = function () {
  85993. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  85994. };
  85995. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  85996. // orientation of a polygon is flipped.
  85997. Vertex.prototype.flip = function () {
  85998. this.normal = this.normal.scale(-1);
  85999. };
  86000. // Create a new vertex between this vertex and `other` by linearly
  86001. // interpolating all properties using a parameter of `t`. Subclasses should
  86002. // override this to interpolate additional properties.
  86003. Vertex.prototype.interpolate = function (other, t) {
  86004. 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));
  86005. };
  86006. return Vertex;
  86007. }());
  86008. // # class Plane
  86009. // Represents a plane in 3D space.
  86010. var Plane = /** @class */ (function () {
  86011. function Plane(normal, w) {
  86012. this.normal = normal;
  86013. this.w = w;
  86014. }
  86015. Plane.FromPoints = function (a, b, c) {
  86016. var v0 = c.subtract(a);
  86017. var v1 = b.subtract(a);
  86018. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  86019. return null;
  86020. }
  86021. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  86022. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  86023. };
  86024. Plane.prototype.clone = function () {
  86025. return new Plane(this.normal.clone(), this.w);
  86026. };
  86027. Plane.prototype.flip = function () {
  86028. this.normal.scaleInPlace(-1);
  86029. this.w = -this.w;
  86030. };
  86031. // Split `polygon` by this plane if needed, then put the polygon or polygon
  86032. // fragments in the appropriate lists. Coplanar polygons go into either
  86033. // `coplanarFront` or `coplanarBack` depending on their orientation with
  86034. // respect to this plane. Polygons in front or in back of this plane go into
  86035. // either `front` or `back`.
  86036. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  86037. var COPLANAR = 0;
  86038. var FRONT = 1;
  86039. var BACK = 2;
  86040. var SPANNING = 3;
  86041. // Classify each point as well as the entire polygon into one of the above
  86042. // four classes.
  86043. var polygonType = 0;
  86044. var types = [];
  86045. var i;
  86046. var t;
  86047. for (i = 0; i < polygon.vertices.length; i++) {
  86048. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  86049. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  86050. polygonType |= type;
  86051. types.push(type);
  86052. }
  86053. // Put the polygon in the correct list, splitting it when necessary.
  86054. switch (polygonType) {
  86055. case COPLANAR:
  86056. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  86057. break;
  86058. case FRONT:
  86059. front.push(polygon);
  86060. break;
  86061. case BACK:
  86062. back.push(polygon);
  86063. break;
  86064. case SPANNING:
  86065. var f = [], b = [];
  86066. for (i = 0; i < polygon.vertices.length; i++) {
  86067. var j = (i + 1) % polygon.vertices.length;
  86068. var ti = types[i], tj = types[j];
  86069. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  86070. if (ti !== BACK)
  86071. f.push(vi);
  86072. if (ti !== FRONT)
  86073. b.push(ti !== BACK ? vi.clone() : vi);
  86074. if ((ti | tj) === SPANNING) {
  86075. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  86076. var v = vi.interpolate(vj, t);
  86077. f.push(v);
  86078. b.push(v.clone());
  86079. }
  86080. }
  86081. var poly;
  86082. if (f.length >= 3) {
  86083. poly = new Polygon(f, polygon.shared);
  86084. if (poly.plane)
  86085. front.push(poly);
  86086. }
  86087. if (b.length >= 3) {
  86088. poly = new Polygon(b, polygon.shared);
  86089. if (poly.plane)
  86090. back.push(poly);
  86091. }
  86092. break;
  86093. }
  86094. };
  86095. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  86096. // point is on the plane.
  86097. Plane.EPSILON = 1e-5;
  86098. return Plane;
  86099. }());
  86100. // # class Polygon
  86101. // Represents a convex polygon. The vertices used to initialize a polygon must
  86102. // be coplanar and form a convex loop.
  86103. //
  86104. // Each convex polygon has a `shared` property, which is shared between all
  86105. // polygons that are clones of each other or were split from the same polygon.
  86106. // This can be used to define per-polygon properties (such as surface color).
  86107. var Polygon = /** @class */ (function () {
  86108. function Polygon(vertices, shared) {
  86109. this.vertices = vertices;
  86110. this.shared = shared;
  86111. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  86112. }
  86113. Polygon.prototype.clone = function () {
  86114. var vertices = this.vertices.map(function (v) { return v.clone(); });
  86115. return new Polygon(vertices, this.shared);
  86116. };
  86117. Polygon.prototype.flip = function () {
  86118. this.vertices.reverse().map(function (v) { v.flip(); });
  86119. this.plane.flip();
  86120. };
  86121. return Polygon;
  86122. }());
  86123. // # class Node
  86124. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  86125. // by picking a polygon to split along. That polygon (and all other coplanar
  86126. // polygons) are added directly to that node and the other polygons are added to
  86127. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  86128. // no distinction between internal and leaf nodes.
  86129. var Node = /** @class */ (function () {
  86130. function Node(polygons) {
  86131. this.plane = null;
  86132. this.front = null;
  86133. this.back = null;
  86134. this.polygons = new Array();
  86135. if (polygons) {
  86136. this.build(polygons);
  86137. }
  86138. }
  86139. Node.prototype.clone = function () {
  86140. var node = new Node();
  86141. node.plane = this.plane && this.plane.clone();
  86142. node.front = this.front && this.front.clone();
  86143. node.back = this.back && this.back.clone();
  86144. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  86145. return node;
  86146. };
  86147. // Convert solid space to empty space and empty space to solid space.
  86148. Node.prototype.invert = function () {
  86149. for (var i = 0; i < this.polygons.length; i++) {
  86150. this.polygons[i].flip();
  86151. }
  86152. if (this.plane) {
  86153. this.plane.flip();
  86154. }
  86155. if (this.front) {
  86156. this.front.invert();
  86157. }
  86158. if (this.back) {
  86159. this.back.invert();
  86160. }
  86161. var temp = this.front;
  86162. this.front = this.back;
  86163. this.back = temp;
  86164. };
  86165. // Recursively remove all polygons in `polygons` that are inside this BSP
  86166. // tree.
  86167. Node.prototype.clipPolygons = function (polygons) {
  86168. if (!this.plane)
  86169. return polygons.slice();
  86170. var front = new Array(), back = new Array();
  86171. for (var i = 0; i < polygons.length; i++) {
  86172. this.plane.splitPolygon(polygons[i], front, back, front, back);
  86173. }
  86174. if (this.front) {
  86175. front = this.front.clipPolygons(front);
  86176. }
  86177. if (this.back) {
  86178. back = this.back.clipPolygons(back);
  86179. }
  86180. else {
  86181. back = [];
  86182. }
  86183. return front.concat(back);
  86184. };
  86185. // Remove all polygons in this BSP tree that are inside the other BSP tree
  86186. // `bsp`.
  86187. Node.prototype.clipTo = function (bsp) {
  86188. this.polygons = bsp.clipPolygons(this.polygons);
  86189. if (this.front)
  86190. this.front.clipTo(bsp);
  86191. if (this.back)
  86192. this.back.clipTo(bsp);
  86193. };
  86194. // Return a list of all polygons in this BSP tree.
  86195. Node.prototype.allPolygons = function () {
  86196. var polygons = this.polygons.slice();
  86197. if (this.front)
  86198. polygons = polygons.concat(this.front.allPolygons());
  86199. if (this.back)
  86200. polygons = polygons.concat(this.back.allPolygons());
  86201. return polygons;
  86202. };
  86203. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  86204. // new polygons are filtered down to the bottom of the tree and become new
  86205. // nodes there. Each set of polygons is partitioned using the first polygon
  86206. // (no heuristic is used to pick a good split).
  86207. Node.prototype.build = function (polygons) {
  86208. if (!polygons.length)
  86209. return;
  86210. if (!this.plane)
  86211. this.plane = polygons[0].plane.clone();
  86212. var front = new Array(), back = new Array();
  86213. for (var i = 0; i < polygons.length; i++) {
  86214. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  86215. }
  86216. if (front.length) {
  86217. if (!this.front)
  86218. this.front = new Node();
  86219. this.front.build(front);
  86220. }
  86221. if (back.length) {
  86222. if (!this.back)
  86223. this.back = new Node();
  86224. this.back.build(back);
  86225. }
  86226. };
  86227. return Node;
  86228. }());
  86229. var CSG = /** @class */ (function () {
  86230. function CSG() {
  86231. this.polygons = new Array();
  86232. }
  86233. // Convert BABYLON.Mesh to BABYLON.CSG
  86234. CSG.FromMesh = function (mesh) {
  86235. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  86236. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  86237. if (mesh instanceof BABYLON.Mesh) {
  86238. mesh.computeWorldMatrix(true);
  86239. matrix = mesh.getWorldMatrix();
  86240. meshPosition = mesh.position.clone();
  86241. meshRotation = mesh.rotation.clone();
  86242. if (mesh.rotationQuaternion) {
  86243. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  86244. }
  86245. meshScaling = mesh.scaling.clone();
  86246. }
  86247. else {
  86248. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  86249. }
  86250. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  86251. var subMeshes = mesh.subMeshes;
  86252. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  86253. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  86254. vertices = [];
  86255. for (var j = 0; j < 3; j++) {
  86256. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  86257. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  86258. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  86259. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  86260. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  86261. vertex = new Vertex(position, normal, uv);
  86262. vertices.push(vertex);
  86263. }
  86264. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  86265. // To handle the case of degenerated triangle
  86266. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  86267. if (polygon.plane)
  86268. polygons.push(polygon);
  86269. }
  86270. }
  86271. var csg = CSG.FromPolygons(polygons);
  86272. csg.matrix = matrix;
  86273. csg.position = meshPosition;
  86274. csg.rotation = meshRotation;
  86275. csg.scaling = meshScaling;
  86276. csg.rotationQuaternion = meshRotationQuaternion;
  86277. currentCSGMeshId++;
  86278. return csg;
  86279. };
  86280. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  86281. CSG.FromPolygons = function (polygons) {
  86282. var csg = new CSG();
  86283. csg.polygons = polygons;
  86284. return csg;
  86285. };
  86286. CSG.prototype.clone = function () {
  86287. var csg = new CSG();
  86288. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  86289. csg.copyTransformAttributes(this);
  86290. return csg;
  86291. };
  86292. CSG.prototype.union = function (csg) {
  86293. var a = new Node(this.clone().polygons);
  86294. var b = new Node(csg.clone().polygons);
  86295. a.clipTo(b);
  86296. b.clipTo(a);
  86297. b.invert();
  86298. b.clipTo(a);
  86299. b.invert();
  86300. a.build(b.allPolygons());
  86301. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  86302. };
  86303. CSG.prototype.unionInPlace = function (csg) {
  86304. var a = new Node(this.polygons);
  86305. var b = new Node(csg.polygons);
  86306. a.clipTo(b);
  86307. b.clipTo(a);
  86308. b.invert();
  86309. b.clipTo(a);
  86310. b.invert();
  86311. a.build(b.allPolygons());
  86312. this.polygons = a.allPolygons();
  86313. };
  86314. CSG.prototype.subtract = function (csg) {
  86315. var a = new Node(this.clone().polygons);
  86316. var b = new Node(csg.clone().polygons);
  86317. a.invert();
  86318. a.clipTo(b);
  86319. b.clipTo(a);
  86320. b.invert();
  86321. b.clipTo(a);
  86322. b.invert();
  86323. a.build(b.allPolygons());
  86324. a.invert();
  86325. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  86326. };
  86327. CSG.prototype.subtractInPlace = function (csg) {
  86328. var a = new Node(this.polygons);
  86329. var b = new Node(csg.polygons);
  86330. a.invert();
  86331. a.clipTo(b);
  86332. b.clipTo(a);
  86333. b.invert();
  86334. b.clipTo(a);
  86335. b.invert();
  86336. a.build(b.allPolygons());
  86337. a.invert();
  86338. this.polygons = a.allPolygons();
  86339. };
  86340. CSG.prototype.intersect = function (csg) {
  86341. var a = new Node(this.clone().polygons);
  86342. var b = new Node(csg.clone().polygons);
  86343. a.invert();
  86344. b.clipTo(a);
  86345. b.invert();
  86346. a.clipTo(b);
  86347. b.clipTo(a);
  86348. a.build(b.allPolygons());
  86349. a.invert();
  86350. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  86351. };
  86352. CSG.prototype.intersectInPlace = function (csg) {
  86353. var a = new Node(this.polygons);
  86354. var b = new Node(csg.polygons);
  86355. a.invert();
  86356. b.clipTo(a);
  86357. b.invert();
  86358. a.clipTo(b);
  86359. b.clipTo(a);
  86360. a.build(b.allPolygons());
  86361. a.invert();
  86362. this.polygons = a.allPolygons();
  86363. };
  86364. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  86365. // not modified.
  86366. CSG.prototype.inverse = function () {
  86367. var csg = this.clone();
  86368. csg.inverseInPlace();
  86369. return csg;
  86370. };
  86371. CSG.prototype.inverseInPlace = function () {
  86372. this.polygons.map(function (p) { p.flip(); });
  86373. };
  86374. // This is used to keep meshes transformations so they can be restored
  86375. // when we build back a Babylon Mesh
  86376. // NB : All CSG operations are performed in world coordinates
  86377. CSG.prototype.copyTransformAttributes = function (csg) {
  86378. this.matrix = csg.matrix;
  86379. this.position = csg.position;
  86380. this.rotation = csg.rotation;
  86381. this.scaling = csg.scaling;
  86382. this.rotationQuaternion = csg.rotationQuaternion;
  86383. return this;
  86384. };
  86385. // Build Raw mesh from CSG
  86386. // Coordinates here are in world space
  86387. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  86388. var matrix = this.matrix.clone();
  86389. matrix.invert();
  86390. 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;
  86391. if (keepSubMeshes) {
  86392. // Sort Polygons, since subMeshes are indices range
  86393. polygons.sort(function (a, b) {
  86394. if (a.shared.meshId === b.shared.meshId) {
  86395. return a.shared.subMeshId - b.shared.subMeshId;
  86396. }
  86397. else {
  86398. return a.shared.meshId - b.shared.meshId;
  86399. }
  86400. });
  86401. }
  86402. for (var i = 0, il = polygons.length; i < il; i++) {
  86403. polygon = polygons[i];
  86404. // Building SubMeshes
  86405. if (!subMesh_dict[polygon.shared.meshId]) {
  86406. subMesh_dict[polygon.shared.meshId] = {};
  86407. }
  86408. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  86409. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  86410. indexStart: +Infinity,
  86411. indexEnd: -Infinity,
  86412. materialIndex: polygon.shared.materialIndex
  86413. };
  86414. }
  86415. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  86416. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  86417. polygonIndices[0] = 0;
  86418. polygonIndices[1] = j - 1;
  86419. polygonIndices[2] = j;
  86420. for (var k = 0; k < 3; k++) {
  86421. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  86422. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  86423. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  86424. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  86425. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  86426. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  86427. // Check if 2 points can be merged
  86428. if (!(typeof vertex_idx !== 'undefined' &&
  86429. normals[vertex_idx * 3] === localNormal.x &&
  86430. normals[vertex_idx * 3 + 1] === localNormal.y &&
  86431. normals[vertex_idx * 3 + 2] === localNormal.z &&
  86432. uvs[vertex_idx * 2] === uv.x &&
  86433. uvs[vertex_idx * 2 + 1] === uv.y)) {
  86434. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  86435. uvs.push(uv.x, uv.y);
  86436. normals.push(normal.x, normal.y, normal.z);
  86437. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  86438. }
  86439. indices.push(vertex_idx);
  86440. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  86441. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  86442. currentIndex++;
  86443. }
  86444. }
  86445. }
  86446. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  86447. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  86448. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  86449. mesh.setIndices(indices, null);
  86450. if (keepSubMeshes) {
  86451. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  86452. var materialIndexOffset = 0, materialMaxIndex;
  86453. mesh.subMeshes = new Array();
  86454. for (var m in subMesh_dict) {
  86455. materialMaxIndex = -1;
  86456. for (var sm in subMesh_dict[m]) {
  86457. subMesh_obj = subMesh_dict[m][sm];
  86458. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  86459. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  86460. }
  86461. materialIndexOffset += ++materialMaxIndex;
  86462. }
  86463. }
  86464. return mesh;
  86465. };
  86466. // Build Mesh from CSG taking material and transforms into account
  86467. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  86468. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  86469. mesh.material = material;
  86470. mesh.position.copyFrom(this.position);
  86471. mesh.rotation.copyFrom(this.rotation);
  86472. if (this.rotationQuaternion) {
  86473. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  86474. }
  86475. mesh.scaling.copyFrom(this.scaling);
  86476. mesh.computeWorldMatrix(true);
  86477. return mesh;
  86478. };
  86479. return CSG;
  86480. }());
  86481. BABYLON.CSG = CSG;
  86482. })(BABYLON || (BABYLON = {}));
  86483. //# sourceMappingURL=babylon.csg.js.map
  86484. var BABYLON;
  86485. (function (BABYLON) {
  86486. var LensFlare = /** @class */ (function () {
  86487. function LensFlare(size, position, color, imgUrl, system) {
  86488. this.size = size;
  86489. this.position = position;
  86490. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  86491. this.color = color || new BABYLON.Color3(1, 1, 1);
  86492. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  86493. this._system = system;
  86494. system.lensFlares.push(this);
  86495. }
  86496. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  86497. return new LensFlare(size, position, color, imgUrl, system);
  86498. };
  86499. LensFlare.prototype.dispose = function () {
  86500. if (this.texture) {
  86501. this.texture.dispose();
  86502. }
  86503. // Remove from scene
  86504. var index = this._system.lensFlares.indexOf(this);
  86505. this._system.lensFlares.splice(index, 1);
  86506. };
  86507. ;
  86508. return LensFlare;
  86509. }());
  86510. BABYLON.LensFlare = LensFlare;
  86511. })(BABYLON || (BABYLON = {}));
  86512. //# sourceMappingURL=babylon.lensFlare.js.map
  86513. var BABYLON;
  86514. (function (BABYLON) {
  86515. // Adds the parser to the scene parsers.
  86516. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  86517. // Lens flares
  86518. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  86519. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  86520. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  86521. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  86522. container.lensFlareSystems.push(lf);
  86523. }
  86524. }
  86525. });
  86526. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  86527. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  86528. if (this.lensFlareSystems[index].name === name) {
  86529. return this.lensFlareSystems[index];
  86530. }
  86531. }
  86532. return null;
  86533. };
  86534. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  86535. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  86536. if (this.lensFlareSystems[index].id === id) {
  86537. return this.lensFlareSystems[index];
  86538. }
  86539. }
  86540. return null;
  86541. };
  86542. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  86543. var index = this.lensFlareSystems.indexOf(toRemove);
  86544. if (index !== -1) {
  86545. this.lensFlareSystems.splice(index, 1);
  86546. }
  86547. return index;
  86548. };
  86549. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  86550. this.lensFlareSystems.push(newLensFlareSystem);
  86551. };
  86552. /**
  86553. * Defines the lens flare scene component responsible to manage any lens flares
  86554. * in a given scene.
  86555. */
  86556. var LensFlareSystemSceneComponent = /** @class */ (function () {
  86557. /**
  86558. * Creates a new instance of the component for the given scene
  86559. * @param scene Defines the scene to register the component in
  86560. */
  86561. function LensFlareSystemSceneComponent(scene) {
  86562. /**
  86563. * The component name helpfull to identify the component in the list of scene components.
  86564. */
  86565. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  86566. this.scene = scene;
  86567. scene.lensFlareSystems = new Array();
  86568. }
  86569. /**
  86570. * Registers the component in a given scene
  86571. */
  86572. LensFlareSystemSceneComponent.prototype.register = function () {
  86573. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  86574. };
  86575. /**
  86576. * Rebuilds the elements related to this component in case of
  86577. * context lost for instance.
  86578. */
  86579. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  86580. // Nothing to do for lens flare
  86581. };
  86582. /**
  86583. * Adds all the element from the container to the scene
  86584. * @param container the container holding the elements
  86585. */
  86586. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  86587. var _this = this;
  86588. if (!container.lensFlareSystems) {
  86589. return;
  86590. }
  86591. container.lensFlareSystems.forEach(function (o) {
  86592. _this.scene.addLensFlareSystem(o);
  86593. });
  86594. };
  86595. /**
  86596. * Removes all the elements in the container from the scene
  86597. * @param container contains the elements to remove
  86598. */
  86599. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  86600. var _this = this;
  86601. if (!container.lensFlareSystems) {
  86602. return;
  86603. }
  86604. container.lensFlareSystems.forEach(function (o) {
  86605. _this.scene.removeLensFlareSystem(o);
  86606. });
  86607. };
  86608. /**
  86609. * Serializes the component data to the specified json object
  86610. * @param serializationObject The object to serialize to
  86611. */
  86612. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  86613. // Lens flares
  86614. serializationObject.lensFlareSystems = [];
  86615. var lensFlareSystems = this.scene.lensFlareSystems;
  86616. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  86617. var lensFlareSystem = lensFlareSystems_1[_i];
  86618. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  86619. }
  86620. };
  86621. /**
  86622. * Disposes the component and the associated ressources.
  86623. */
  86624. LensFlareSystemSceneComponent.prototype.dispose = function () {
  86625. var lensFlareSystems = this.scene.lensFlareSystems;
  86626. while (lensFlareSystems.length) {
  86627. lensFlareSystems[0].dispose();
  86628. }
  86629. };
  86630. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  86631. // Lens flares
  86632. if (this.scene.lensFlaresEnabled) {
  86633. var lensFlareSystems = this.scene.lensFlareSystems;
  86634. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  86635. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  86636. var lensFlareSystem = lensFlareSystems_2[_i];
  86637. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  86638. lensFlareSystem.render();
  86639. }
  86640. }
  86641. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  86642. }
  86643. };
  86644. return LensFlareSystemSceneComponent;
  86645. }());
  86646. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  86647. })(BABYLON || (BABYLON = {}));
  86648. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  86649. var BABYLON;
  86650. (function (BABYLON) {
  86651. var LensFlareSystem = /** @class */ (function () {
  86652. function LensFlareSystem(name, emitter, scene) {
  86653. this.name = name;
  86654. this.lensFlares = new Array();
  86655. this.borderLimit = 300;
  86656. this.viewportBorder = 0;
  86657. this.layerMask = 0x0FFFFFFF;
  86658. this._vertexBuffers = {};
  86659. this._isEnabled = true;
  86660. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86661. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  86662. if (!component) {
  86663. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  86664. scene._addComponent(component);
  86665. }
  86666. this._emitter = emitter;
  86667. this.id = name;
  86668. scene.lensFlareSystems.push(this);
  86669. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  86670. var engine = scene.getEngine();
  86671. // VBO
  86672. var vertices = [];
  86673. vertices.push(1, 1);
  86674. vertices.push(-1, 1);
  86675. vertices.push(-1, -1);
  86676. vertices.push(1, -1);
  86677. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86678. // Indices
  86679. var indices = [];
  86680. indices.push(0);
  86681. indices.push(1);
  86682. indices.push(2);
  86683. indices.push(0);
  86684. indices.push(2);
  86685. indices.push(3);
  86686. this._indexBuffer = engine.createIndexBuffer(indices);
  86687. // Effects
  86688. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  86689. }
  86690. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  86691. get: function () {
  86692. return this._isEnabled;
  86693. },
  86694. set: function (value) {
  86695. this._isEnabled = value;
  86696. },
  86697. enumerable: true,
  86698. configurable: true
  86699. });
  86700. LensFlareSystem.prototype.getScene = function () {
  86701. return this._scene;
  86702. };
  86703. LensFlareSystem.prototype.getEmitter = function () {
  86704. return this._emitter;
  86705. };
  86706. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  86707. this._emitter = newEmitter;
  86708. };
  86709. LensFlareSystem.prototype.getEmitterPosition = function () {
  86710. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  86711. };
  86712. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  86713. var position = this.getEmitterPosition();
  86714. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  86715. this._positionX = position.x;
  86716. this._positionY = position.y;
  86717. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  86718. if (this.viewportBorder > 0) {
  86719. globalViewport.x -= this.viewportBorder;
  86720. globalViewport.y -= this.viewportBorder;
  86721. globalViewport.width += this.viewportBorder * 2;
  86722. globalViewport.height += this.viewportBorder * 2;
  86723. position.x += this.viewportBorder;
  86724. position.y += this.viewportBorder;
  86725. this._positionX += this.viewportBorder;
  86726. this._positionY += this.viewportBorder;
  86727. }
  86728. if (position.z > 0) {
  86729. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  86730. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  86731. return true;
  86732. }
  86733. return true;
  86734. }
  86735. return false;
  86736. };
  86737. /** @hidden */
  86738. LensFlareSystem.prototype._isVisible = function () {
  86739. if (!this._isEnabled || !this._scene.activeCamera) {
  86740. return false;
  86741. }
  86742. var emitterPosition = this.getEmitterPosition();
  86743. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  86744. var distance = direction.length();
  86745. direction.normalize();
  86746. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  86747. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  86748. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  86749. };
  86750. LensFlareSystem.prototype.render = function () {
  86751. if (!this._effect.isReady() || !this._scene.activeCamera)
  86752. return false;
  86753. var engine = this._scene.getEngine();
  86754. var viewport = this._scene.activeCamera.viewport;
  86755. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  86756. // Position
  86757. if (!this.computeEffectivePosition(globalViewport)) {
  86758. return false;
  86759. }
  86760. // Visibility
  86761. if (!this._isVisible()) {
  86762. return false;
  86763. }
  86764. // Intensity
  86765. var awayX;
  86766. var awayY;
  86767. if (this._positionX < this.borderLimit + globalViewport.x) {
  86768. awayX = this.borderLimit + globalViewport.x - this._positionX;
  86769. }
  86770. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  86771. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  86772. }
  86773. else {
  86774. awayX = 0;
  86775. }
  86776. if (this._positionY < this.borderLimit + globalViewport.y) {
  86777. awayY = this.borderLimit + globalViewport.y - this._positionY;
  86778. }
  86779. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  86780. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  86781. }
  86782. else {
  86783. awayY = 0;
  86784. }
  86785. var away = (awayX > awayY) ? awayX : awayY;
  86786. away -= this.viewportBorder;
  86787. if (away > this.borderLimit) {
  86788. away = this.borderLimit;
  86789. }
  86790. var intensity = 1.0 - (away / this.borderLimit);
  86791. if (intensity < 0) {
  86792. return false;
  86793. }
  86794. if (intensity > 1.0) {
  86795. intensity = 1.0;
  86796. }
  86797. if (this.viewportBorder > 0) {
  86798. globalViewport.x += this.viewportBorder;
  86799. globalViewport.y += this.viewportBorder;
  86800. globalViewport.width -= this.viewportBorder * 2;
  86801. globalViewport.height -= this.viewportBorder * 2;
  86802. this._positionX -= this.viewportBorder;
  86803. this._positionY -= this.viewportBorder;
  86804. }
  86805. // Position
  86806. var centerX = globalViewport.x + globalViewport.width / 2;
  86807. var centerY = globalViewport.y + globalViewport.height / 2;
  86808. var distX = centerX - this._positionX;
  86809. var distY = centerY - this._positionY;
  86810. // Effects
  86811. engine.enableEffect(this._effect);
  86812. engine.setState(false);
  86813. engine.setDepthBuffer(false);
  86814. // VBOs
  86815. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  86816. // Flares
  86817. for (var index = 0; index < this.lensFlares.length; index++) {
  86818. var flare = this.lensFlares[index];
  86819. engine.setAlphaMode(flare.alphaMode);
  86820. var x = centerX - (distX * flare.position);
  86821. var y = centerY - (distY * flare.position);
  86822. var cw = flare.size;
  86823. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  86824. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  86825. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  86826. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  86827. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  86828. // Texture
  86829. this._effect.setTexture("textureSampler", flare.texture);
  86830. // Color
  86831. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  86832. // Draw order
  86833. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86834. }
  86835. engine.setDepthBuffer(true);
  86836. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86837. return true;
  86838. };
  86839. LensFlareSystem.prototype.dispose = function () {
  86840. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86841. if (vertexBuffer) {
  86842. vertexBuffer.dispose();
  86843. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86844. }
  86845. if (this._indexBuffer) {
  86846. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86847. this._indexBuffer = null;
  86848. }
  86849. while (this.lensFlares.length) {
  86850. this.lensFlares[0].dispose();
  86851. }
  86852. // Remove from scene
  86853. var index = this._scene.lensFlareSystems.indexOf(this);
  86854. this._scene.lensFlareSystems.splice(index, 1);
  86855. };
  86856. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  86857. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  86858. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  86859. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  86860. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  86861. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  86862. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  86863. var parsedFlare = parsedLensFlareSystem.flares[index];
  86864. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  86865. }
  86866. return lensFlareSystem;
  86867. };
  86868. LensFlareSystem.prototype.serialize = function () {
  86869. var serializationObject = {};
  86870. serializationObject.id = this.id;
  86871. serializationObject.name = this.name;
  86872. serializationObject.emitterId = this.getEmitter().id;
  86873. serializationObject.borderLimit = this.borderLimit;
  86874. serializationObject.flares = [];
  86875. for (var index = 0; index < this.lensFlares.length; index++) {
  86876. var flare = this.lensFlares[index];
  86877. serializationObject.flares.push({
  86878. size: flare.size,
  86879. position: flare.position,
  86880. color: flare.color.asArray(),
  86881. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  86882. });
  86883. }
  86884. return serializationObject;
  86885. };
  86886. return LensFlareSystem;
  86887. }());
  86888. BABYLON.LensFlareSystem = LensFlareSystem;
  86889. })(BABYLON || (BABYLON = {}));
  86890. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  86891. var BABYLON;
  86892. (function (BABYLON) {
  86893. /**
  86894. * This is a holder class for the physics joint created by the physics plugin.
  86895. * It holds a set of functions to control the underlying joint.
  86896. */
  86897. var PhysicsJoint = /** @class */ (function () {
  86898. function PhysicsJoint(type, jointData) {
  86899. this.type = type;
  86900. this.jointData = jointData;
  86901. jointData.nativeParams = jointData.nativeParams || {};
  86902. }
  86903. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  86904. get: function () {
  86905. return this._physicsJoint;
  86906. },
  86907. set: function (newJoint) {
  86908. if (this._physicsJoint) {
  86909. //remove from the wolrd
  86910. }
  86911. this._physicsJoint = newJoint;
  86912. },
  86913. enumerable: true,
  86914. configurable: true
  86915. });
  86916. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  86917. set: function (physicsPlugin) {
  86918. this._physicsPlugin = physicsPlugin;
  86919. },
  86920. enumerable: true,
  86921. configurable: true
  86922. });
  86923. /**
  86924. * Execute a function that is physics-plugin specific.
  86925. * @param {Function} func the function that will be executed.
  86926. * It accepts two parameters: the physics world and the physics joint.
  86927. */
  86928. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  86929. func(this._physicsPlugin.world, this._physicsJoint);
  86930. };
  86931. //TODO check if the native joints are the same
  86932. //Joint Types
  86933. PhysicsJoint.DistanceJoint = 0;
  86934. PhysicsJoint.HingeJoint = 1;
  86935. PhysicsJoint.BallAndSocketJoint = 2;
  86936. PhysicsJoint.WheelJoint = 3;
  86937. PhysicsJoint.SliderJoint = 4;
  86938. //OIMO
  86939. PhysicsJoint.PrismaticJoint = 5;
  86940. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  86941. PhysicsJoint.UniversalJoint = 6;
  86942. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  86943. //Cannon
  86944. //Similar to a Ball-Joint. Different in params
  86945. PhysicsJoint.PointToPointJoint = 8;
  86946. //Cannon only at the moment
  86947. PhysicsJoint.SpringJoint = 9;
  86948. PhysicsJoint.LockJoint = 10;
  86949. return PhysicsJoint;
  86950. }());
  86951. BABYLON.PhysicsJoint = PhysicsJoint;
  86952. /**
  86953. * A class representing a physics distance joint.
  86954. */
  86955. var DistanceJoint = /** @class */ (function (_super) {
  86956. __extends(DistanceJoint, _super);
  86957. function DistanceJoint(jointData) {
  86958. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  86959. }
  86960. /**
  86961. * Update the predefined distance.
  86962. */
  86963. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  86964. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  86965. };
  86966. return DistanceJoint;
  86967. }(PhysicsJoint));
  86968. BABYLON.DistanceJoint = DistanceJoint;
  86969. var MotorEnabledJoint = /** @class */ (function (_super) {
  86970. __extends(MotorEnabledJoint, _super);
  86971. function MotorEnabledJoint(type, jointData) {
  86972. return _super.call(this, type, jointData) || this;
  86973. }
  86974. /**
  86975. * Set the motor values.
  86976. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86977. * @param {number} force the force to apply
  86978. * @param {number} maxForce max force for this motor.
  86979. */
  86980. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  86981. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  86982. };
  86983. /**
  86984. * Set the motor's limits.
  86985. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86986. */
  86987. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  86988. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  86989. };
  86990. return MotorEnabledJoint;
  86991. }(PhysicsJoint));
  86992. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  86993. /**
  86994. * This class represents a single hinge physics joint
  86995. */
  86996. var HingeJoint = /** @class */ (function (_super) {
  86997. __extends(HingeJoint, _super);
  86998. function HingeJoint(jointData) {
  86999. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  87000. }
  87001. /**
  87002. * Set the motor values.
  87003. * Attention, this function is plugin specific. Engines won't react 100% the same.
  87004. * @param {number} force the force to apply
  87005. * @param {number} maxForce max force for this motor.
  87006. */
  87007. HingeJoint.prototype.setMotor = function (force, maxForce) {
  87008. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  87009. };
  87010. /**
  87011. * Set the motor's limits.
  87012. * Attention, this function is plugin specific. Engines won't react 100% the same.
  87013. */
  87014. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  87015. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  87016. };
  87017. return HingeJoint;
  87018. }(MotorEnabledJoint));
  87019. BABYLON.HingeJoint = HingeJoint;
  87020. /**
  87021. * This class represents a dual hinge physics joint (same as wheel joint)
  87022. */
  87023. var Hinge2Joint = /** @class */ (function (_super) {
  87024. __extends(Hinge2Joint, _super);
  87025. function Hinge2Joint(jointData) {
  87026. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  87027. }
  87028. /**
  87029. * Set the motor values.
  87030. * Attention, this function is plugin specific. Engines won't react 100% the same.
  87031. * @param {number} force the force to apply
  87032. * @param {number} maxForce max force for this motor.
  87033. * @param {motorIndex} the motor's index, 0 or 1.
  87034. */
  87035. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  87036. if (motorIndex === void 0) { motorIndex = 0; }
  87037. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  87038. };
  87039. /**
  87040. * Set the motor limits.
  87041. * Attention, this function is plugin specific. Engines won't react 100% the same.
  87042. * @param {number} upperLimit the upper limit
  87043. * @param {number} lowerLimit lower limit
  87044. * @param {motorIndex} the motor's index, 0 or 1.
  87045. */
  87046. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  87047. if (motorIndex === void 0) { motorIndex = 0; }
  87048. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  87049. };
  87050. return Hinge2Joint;
  87051. }(MotorEnabledJoint));
  87052. BABYLON.Hinge2Joint = Hinge2Joint;
  87053. })(BABYLON || (BABYLON = {}));
  87054. //# sourceMappingURL=babylon.physicsJoint.js.map
  87055. var BABYLON;
  87056. (function (BABYLON) {
  87057. var PhysicsImpostor = /** @class */ (function () {
  87058. function PhysicsImpostor(object, type, _options, _scene) {
  87059. if (_options === void 0) { _options = { mass: 0 }; }
  87060. var _this = this;
  87061. this.object = object;
  87062. this.type = type;
  87063. this._options = _options;
  87064. this._scene = _scene;
  87065. this._bodyUpdateRequired = false;
  87066. this._onBeforePhysicsStepCallbacks = new Array();
  87067. this._onAfterPhysicsStepCallbacks = new Array();
  87068. this._onPhysicsCollideCallbacks = [];
  87069. this._deltaPosition = BABYLON.Vector3.Zero();
  87070. this._isDisposed = false;
  87071. //temp variables for parent rotation calculations
  87072. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  87073. this._tmpQuat = new BABYLON.Quaternion();
  87074. this._tmpQuat2 = new BABYLON.Quaternion();
  87075. /**
  87076. * this function is executed by the physics engine.
  87077. */
  87078. this.beforeStep = function () {
  87079. if (!_this._physicsEngine) {
  87080. return;
  87081. }
  87082. _this.object.translate(_this._deltaPosition, -1);
  87083. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  87084. _this.object.computeWorldMatrix(false);
  87085. if (_this.object.parent && _this.object.rotationQuaternion) {
  87086. _this.getParentsRotation();
  87087. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  87088. }
  87089. else {
  87090. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  87091. }
  87092. if (!_this._options.disableBidirectionalTransformation) {
  87093. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  87094. }
  87095. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  87096. func(_this);
  87097. });
  87098. };
  87099. /**
  87100. * this function is executed by the physics engine.
  87101. */
  87102. this.afterStep = function () {
  87103. if (!_this._physicsEngine) {
  87104. return;
  87105. }
  87106. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  87107. func(_this);
  87108. });
  87109. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  87110. // object has now its world rotation. needs to be converted to local.
  87111. if (_this.object.parent && _this.object.rotationQuaternion) {
  87112. _this.getParentsRotation();
  87113. _this._tmpQuat.conjugateInPlace();
  87114. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  87115. }
  87116. // take the position set and make it the absolute position of this object.
  87117. _this.object.setAbsolutePosition(_this.object.position);
  87118. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  87119. _this.object.translate(_this._deltaPosition, 1);
  87120. };
  87121. /**
  87122. * Legacy collision detection event support
  87123. */
  87124. this.onCollideEvent = null;
  87125. //event and body object due to cannon's event-based architecture.
  87126. this.onCollide = function (e) {
  87127. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  87128. return;
  87129. }
  87130. if (!_this._physicsEngine) {
  87131. return;
  87132. }
  87133. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  87134. if (otherImpostor) {
  87135. // Legacy collision detection event support
  87136. if (_this.onCollideEvent) {
  87137. _this.onCollideEvent(_this, otherImpostor);
  87138. }
  87139. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  87140. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  87141. }).forEach(function (obj) {
  87142. obj.callback(_this, otherImpostor);
  87143. });
  87144. }
  87145. };
  87146. //sanity check!
  87147. if (!this.object) {
  87148. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  87149. return;
  87150. }
  87151. //legacy support for old syntax.
  87152. if (!this._scene && object.getScene) {
  87153. this._scene = object.getScene();
  87154. }
  87155. if (!this._scene) {
  87156. return;
  87157. }
  87158. this._physicsEngine = this._scene.getPhysicsEngine();
  87159. if (!this._physicsEngine) {
  87160. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  87161. }
  87162. else {
  87163. //set the object's quaternion, if not set
  87164. if (!this.object.rotationQuaternion) {
  87165. if (this.object.rotation) {
  87166. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  87167. }
  87168. else {
  87169. this.object.rotationQuaternion = new BABYLON.Quaternion();
  87170. }
  87171. }
  87172. //default options params
  87173. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  87174. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  87175. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  87176. this._joints = [];
  87177. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  87178. if (!this.object.parent || this._options.ignoreParent) {
  87179. this._init();
  87180. }
  87181. else if (this.object.parent.physicsImpostor) {
  87182. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  87183. }
  87184. }
  87185. }
  87186. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  87187. get: function () {
  87188. return this._isDisposed;
  87189. },
  87190. enumerable: true,
  87191. configurable: true
  87192. });
  87193. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  87194. get: function () {
  87195. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  87196. },
  87197. set: function (value) {
  87198. this.setMass(value);
  87199. },
  87200. enumerable: true,
  87201. configurable: true
  87202. });
  87203. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  87204. get: function () {
  87205. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  87206. },
  87207. set: function (value) {
  87208. if (!this._physicsEngine) {
  87209. return;
  87210. }
  87211. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  87212. },
  87213. enumerable: true,
  87214. configurable: true
  87215. });
  87216. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  87217. get: function () {
  87218. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  87219. },
  87220. set: function (value) {
  87221. if (!this._physicsEngine) {
  87222. return;
  87223. }
  87224. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  87225. },
  87226. enumerable: true,
  87227. configurable: true
  87228. });
  87229. /**
  87230. * This function will completly initialize this impostor.
  87231. * It will create a new body - but only if this mesh has no parent.
  87232. * If it has, this impostor will not be used other than to define the impostor
  87233. * of the child mesh.
  87234. * @hidden
  87235. */
  87236. PhysicsImpostor.prototype._init = function () {
  87237. if (!this._physicsEngine) {
  87238. return;
  87239. }
  87240. this._physicsEngine.removeImpostor(this);
  87241. this.physicsBody = null;
  87242. this._parent = this._parent || this._getPhysicsParent();
  87243. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  87244. this._physicsEngine.addImpostor(this);
  87245. }
  87246. };
  87247. PhysicsImpostor.prototype._getPhysicsParent = function () {
  87248. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  87249. var parentMesh = this.object.parent;
  87250. return parentMesh.physicsImpostor;
  87251. }
  87252. return null;
  87253. };
  87254. /**
  87255. * Should a new body be generated.
  87256. */
  87257. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  87258. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  87259. };
  87260. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  87261. this.forceUpdate();
  87262. };
  87263. /**
  87264. * Force a regeneration of this or the parent's impostor's body.
  87265. * Use under cautious - This will remove all joints already implemented.
  87266. */
  87267. PhysicsImpostor.prototype.forceUpdate = function () {
  87268. this._init();
  87269. if (this.parent && !this._options.ignoreParent) {
  87270. this.parent.forceUpdate();
  87271. }
  87272. };
  87273. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  87274. /*public get mesh(): AbstractMesh {
  87275. return this._mesh;
  87276. }*/
  87277. /**
  87278. * Gets the body that holds this impostor. Either its own, or its parent.
  87279. */
  87280. get: function () {
  87281. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  87282. },
  87283. /**
  87284. * Set the physics body. Used mainly by the physics engine/plugin
  87285. */
  87286. set: function (physicsBody) {
  87287. if (this._physicsBody && this._physicsEngine) {
  87288. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  87289. }
  87290. this._physicsBody = physicsBody;
  87291. this.resetUpdateFlags();
  87292. },
  87293. enumerable: true,
  87294. configurable: true
  87295. });
  87296. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  87297. get: function () {
  87298. return !this._options.ignoreParent && this._parent ? this._parent : null;
  87299. },
  87300. set: function (value) {
  87301. this._parent = value;
  87302. },
  87303. enumerable: true,
  87304. configurable: true
  87305. });
  87306. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  87307. this._bodyUpdateRequired = false;
  87308. };
  87309. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  87310. if (this.object.getBoundingInfo) {
  87311. var q = this.object.rotationQuaternion;
  87312. //reset rotation
  87313. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  87314. //calculate the world matrix with no rotation
  87315. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  87316. var boundingInfo = this.object.getBoundingInfo();
  87317. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  87318. //bring back the rotation
  87319. this.object.rotationQuaternion = q;
  87320. //calculate the world matrix with the new rotation
  87321. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  87322. return size;
  87323. }
  87324. else {
  87325. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  87326. }
  87327. };
  87328. PhysicsImpostor.prototype.getObjectCenter = function () {
  87329. if (this.object.getBoundingInfo) {
  87330. var boundingInfo = this.object.getBoundingInfo();
  87331. return boundingInfo.boundingBox.centerWorld;
  87332. }
  87333. else {
  87334. return this.object.position;
  87335. }
  87336. };
  87337. /**
  87338. * Get a specific parametes from the options parameter.
  87339. */
  87340. PhysicsImpostor.prototype.getParam = function (paramName) {
  87341. return this._options[paramName];
  87342. };
  87343. /**
  87344. * Sets a specific parameter in the options given to the physics plugin
  87345. */
  87346. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  87347. this._options[paramName] = value;
  87348. this._bodyUpdateRequired = true;
  87349. };
  87350. /**
  87351. * Specifically change the body's mass option. Won't recreate the physics body object
  87352. */
  87353. PhysicsImpostor.prototype.setMass = function (mass) {
  87354. if (this.getParam("mass") !== mass) {
  87355. this.setParam("mass", mass);
  87356. }
  87357. if (this._physicsEngine) {
  87358. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  87359. }
  87360. };
  87361. PhysicsImpostor.prototype.getLinearVelocity = function () {
  87362. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  87363. };
  87364. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  87365. if (this._physicsEngine) {
  87366. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  87367. }
  87368. };
  87369. PhysicsImpostor.prototype.getAngularVelocity = function () {
  87370. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  87371. };
  87372. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  87373. if (this._physicsEngine) {
  87374. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  87375. }
  87376. };
  87377. /**
  87378. * Execute a function with the physics plugin native code.
  87379. * Provide a function the will have two variables - the world object and the physics body object.
  87380. */
  87381. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  87382. if (this._physicsEngine) {
  87383. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  87384. }
  87385. };
  87386. /**
  87387. * Register a function that will be executed before the physics world is stepping forward.
  87388. */
  87389. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  87390. this._onBeforePhysicsStepCallbacks.push(func);
  87391. };
  87392. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  87393. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  87394. if (index > -1) {
  87395. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  87396. }
  87397. else {
  87398. BABYLON.Tools.Warn("Function to remove was not found");
  87399. }
  87400. };
  87401. /**
  87402. * Register a function that will be executed after the physics step
  87403. */
  87404. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  87405. this._onAfterPhysicsStepCallbacks.push(func);
  87406. };
  87407. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  87408. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  87409. if (index > -1) {
  87410. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  87411. }
  87412. else {
  87413. BABYLON.Tools.Warn("Function to remove was not found");
  87414. }
  87415. };
  87416. /**
  87417. * register a function that will be executed when this impostor collides against a different body.
  87418. */
  87419. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  87420. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  87421. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  87422. };
  87423. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  87424. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  87425. var index = -1;
  87426. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  87427. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  87428. // chcek the arrays match
  87429. var sameList = cbDef.otherImpostors.every(function (impostor) {
  87430. return collidedAgainstList.indexOf(impostor) > -1;
  87431. });
  87432. if (sameList) {
  87433. index = idx;
  87434. }
  87435. return sameList;
  87436. }
  87437. return false;
  87438. });
  87439. if (found) {
  87440. this._onPhysicsCollideCallbacks.splice(index, 1);
  87441. }
  87442. else {
  87443. BABYLON.Tools.Warn("Function to remove was not found");
  87444. }
  87445. };
  87446. PhysicsImpostor.prototype.getParentsRotation = function () {
  87447. var parent = this.object.parent;
  87448. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  87449. while (parent) {
  87450. if (parent.rotationQuaternion) {
  87451. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  87452. }
  87453. else {
  87454. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  87455. }
  87456. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  87457. parent = parent.parent;
  87458. }
  87459. return this._tmpQuat;
  87460. };
  87461. /**
  87462. * Apply a force
  87463. */
  87464. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  87465. if (this._physicsEngine) {
  87466. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  87467. }
  87468. return this;
  87469. };
  87470. /**
  87471. * Apply an impulse
  87472. */
  87473. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  87474. if (this._physicsEngine) {
  87475. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  87476. }
  87477. return this;
  87478. };
  87479. /**
  87480. * A help function to create a joint.
  87481. */
  87482. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  87483. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  87484. this.addJoint(otherImpostor, joint);
  87485. return this;
  87486. };
  87487. /**
  87488. * Add a joint to this impostor with a different impostor.
  87489. */
  87490. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  87491. this._joints.push({
  87492. otherImpostor: otherImpostor,
  87493. joint: joint
  87494. });
  87495. if (this._physicsEngine) {
  87496. this._physicsEngine.addJoint(this, otherImpostor, joint);
  87497. }
  87498. return this;
  87499. };
  87500. /**
  87501. * Will keep this body still, in a sleep mode.
  87502. */
  87503. PhysicsImpostor.prototype.sleep = function () {
  87504. if (this._physicsEngine) {
  87505. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  87506. }
  87507. return this;
  87508. };
  87509. /**
  87510. * Wake the body up.
  87511. */
  87512. PhysicsImpostor.prototype.wakeUp = function () {
  87513. if (this._physicsEngine) {
  87514. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  87515. }
  87516. return this;
  87517. };
  87518. PhysicsImpostor.prototype.clone = function (newObject) {
  87519. if (!newObject)
  87520. return null;
  87521. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  87522. };
  87523. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  87524. var _this = this;
  87525. //no dispose if no physics engine is available.
  87526. if (!this._physicsEngine) {
  87527. return;
  87528. }
  87529. this._joints.forEach(function (j) {
  87530. if (_this._physicsEngine) {
  87531. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  87532. }
  87533. });
  87534. //dispose the physics body
  87535. this._physicsEngine.removeImpostor(this);
  87536. if (this.parent) {
  87537. this.parent.forceUpdate();
  87538. }
  87539. else {
  87540. /*this._object.getChildMeshes().forEach(function(mesh) {
  87541. if (mesh.physicsImpostor) {
  87542. if (disposeChildren) {
  87543. mesh.physicsImpostor.dispose();
  87544. mesh.physicsImpostor = null;
  87545. }
  87546. }
  87547. })*/
  87548. }
  87549. this._isDisposed = true;
  87550. };
  87551. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  87552. this._deltaPosition.copyFrom(position);
  87553. };
  87554. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  87555. if (!this._deltaRotation) {
  87556. this._deltaRotation = new BABYLON.Quaternion();
  87557. }
  87558. this._deltaRotation.copyFrom(rotation);
  87559. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  87560. };
  87561. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  87562. if (this._physicsEngine) {
  87563. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  87564. }
  87565. return this;
  87566. };
  87567. PhysicsImpostor.prototype.getRadius = function () {
  87568. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  87569. };
  87570. /**
  87571. * Sync a bone with this impostor
  87572. * @param bone The bone to sync to the impostor.
  87573. * @param boneMesh The mesh that the bone is influencing.
  87574. * @param jointPivot The pivot of the joint / bone in local space.
  87575. * @param distToJoint Optional distance from the impostor to the joint.
  87576. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  87577. */
  87578. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  87579. var tempVec = PhysicsImpostor._tmpVecs[0];
  87580. var mesh = this.object;
  87581. if (mesh.rotationQuaternion) {
  87582. if (adjustRotation) {
  87583. var tempQuat = PhysicsImpostor._tmpQuat;
  87584. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  87585. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  87586. }
  87587. else {
  87588. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  87589. }
  87590. }
  87591. tempVec.x = 0;
  87592. tempVec.y = 0;
  87593. tempVec.z = 0;
  87594. if (jointPivot) {
  87595. tempVec.x = jointPivot.x;
  87596. tempVec.y = jointPivot.y;
  87597. tempVec.z = jointPivot.z;
  87598. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  87599. if (distToJoint === undefined || distToJoint === null) {
  87600. distToJoint = jointPivot.length();
  87601. }
  87602. tempVec.x *= distToJoint;
  87603. tempVec.y *= distToJoint;
  87604. tempVec.z *= distToJoint;
  87605. }
  87606. if (bone.getParent()) {
  87607. tempVec.addInPlace(mesh.getAbsolutePosition());
  87608. bone.setAbsolutePosition(tempVec, boneMesh);
  87609. }
  87610. else {
  87611. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  87612. boneMesh.position.x -= tempVec.x;
  87613. boneMesh.position.y -= tempVec.y;
  87614. boneMesh.position.z -= tempVec.z;
  87615. }
  87616. };
  87617. /**
  87618. * Sync impostor to a bone
  87619. * @param bone The bone that the impostor will be synced to.
  87620. * @param boneMesh The mesh that the bone is influencing.
  87621. * @param jointPivot The pivot of the joint / bone in local space.
  87622. * @param distToJoint Optional distance from the impostor to the joint.
  87623. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  87624. * @param boneAxis Optional vector3 axis the bone is aligned with
  87625. */
  87626. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  87627. var mesh = this.object;
  87628. if (mesh.rotationQuaternion) {
  87629. if (adjustRotation) {
  87630. var tempQuat = PhysicsImpostor._tmpQuat;
  87631. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  87632. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  87633. }
  87634. else {
  87635. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  87636. }
  87637. }
  87638. var pos = PhysicsImpostor._tmpVecs[0];
  87639. var boneDir = PhysicsImpostor._tmpVecs[1];
  87640. if (!boneAxis) {
  87641. boneAxis = PhysicsImpostor._tmpVecs[2];
  87642. boneAxis.x = 0;
  87643. boneAxis.y = 1;
  87644. boneAxis.z = 0;
  87645. }
  87646. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  87647. bone.getAbsolutePositionToRef(boneMesh, pos);
  87648. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  87649. distToJoint = jointPivot.length();
  87650. }
  87651. if (distToJoint !== undefined && distToJoint !== null) {
  87652. pos.x += boneDir.x * distToJoint;
  87653. pos.y += boneDir.y * distToJoint;
  87654. pos.z += boneDir.z * distToJoint;
  87655. }
  87656. mesh.setAbsolutePosition(pos);
  87657. };
  87658. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  87659. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  87660. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87661. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  87662. //Impostor types
  87663. PhysicsImpostor.NoImpostor = 0;
  87664. PhysicsImpostor.SphereImpostor = 1;
  87665. PhysicsImpostor.BoxImpostor = 2;
  87666. PhysicsImpostor.PlaneImpostor = 3;
  87667. PhysicsImpostor.MeshImpostor = 4;
  87668. PhysicsImpostor.CylinderImpostor = 7;
  87669. PhysicsImpostor.ParticleImpostor = 8;
  87670. PhysicsImpostor.HeightmapImpostor = 9;
  87671. return PhysicsImpostor;
  87672. }());
  87673. BABYLON.PhysicsImpostor = PhysicsImpostor;
  87674. })(BABYLON || (BABYLON = {}));
  87675. //# sourceMappingURL=babylon.physicsImpostor.js.map
  87676. var BABYLON;
  87677. (function (BABYLON) {
  87678. var PhysicsEngine = /** @class */ (function () {
  87679. function PhysicsEngine(gravity, _physicsPlugin) {
  87680. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  87681. this._physicsPlugin = _physicsPlugin;
  87682. //new methods and parameters
  87683. this._impostors = [];
  87684. this._joints = [];
  87685. if (!this._physicsPlugin.isSupported()) {
  87686. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  87687. + "Please make sure it is included.");
  87688. }
  87689. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  87690. this.setGravity(gravity);
  87691. this.setTimeStep();
  87692. }
  87693. PhysicsEngine.prototype.setGravity = function (gravity) {
  87694. this.gravity = gravity;
  87695. this._physicsPlugin.setGravity(this.gravity);
  87696. };
  87697. /**
  87698. * Set the time step of the physics engine.
  87699. * default is 1/60.
  87700. * To slow it down, enter 1/600 for example.
  87701. * To speed it up, 1/30
  87702. * @param {number} newTimeStep the new timestep to apply to this world.
  87703. */
  87704. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  87705. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  87706. this._physicsPlugin.setTimeStep(newTimeStep);
  87707. };
  87708. /**
  87709. * Get the time step of the physics engine.
  87710. */
  87711. PhysicsEngine.prototype.getTimeStep = function () {
  87712. return this._physicsPlugin.getTimeStep();
  87713. };
  87714. PhysicsEngine.prototype.dispose = function () {
  87715. this._impostors.forEach(function (impostor) {
  87716. impostor.dispose();
  87717. });
  87718. this._physicsPlugin.dispose();
  87719. };
  87720. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  87721. return this._physicsPlugin.name;
  87722. };
  87723. /**
  87724. * Adding a new impostor for the impostor tracking.
  87725. * This will be done by the impostor itself.
  87726. * @param {PhysicsImpostor} impostor the impostor to add
  87727. */
  87728. PhysicsEngine.prototype.addImpostor = function (impostor) {
  87729. impostor.uniqueId = this._impostors.push(impostor);
  87730. //if no parent, generate the body
  87731. if (!impostor.parent) {
  87732. this._physicsPlugin.generatePhysicsBody(impostor);
  87733. }
  87734. };
  87735. /**
  87736. * Remove an impostor from the engine.
  87737. * This impostor and its mesh will not longer be updated by the physics engine.
  87738. * @param {PhysicsImpostor} impostor the impostor to remove
  87739. */
  87740. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  87741. var index = this._impostors.indexOf(impostor);
  87742. if (index > -1) {
  87743. var removed = this._impostors.splice(index, 1);
  87744. //Is it needed?
  87745. if (removed.length) {
  87746. //this will also remove it from the world.
  87747. removed[0].physicsBody = null;
  87748. }
  87749. }
  87750. };
  87751. /**
  87752. * Add a joint to the physics engine
  87753. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  87754. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  87755. * @param {PhysicsJoint} the joint that will connect both impostors.
  87756. */
  87757. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  87758. var impostorJoint = {
  87759. mainImpostor: mainImpostor,
  87760. connectedImpostor: connectedImpostor,
  87761. joint: joint
  87762. };
  87763. joint.physicsPlugin = this._physicsPlugin;
  87764. this._joints.push(impostorJoint);
  87765. this._physicsPlugin.generateJoint(impostorJoint);
  87766. };
  87767. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  87768. var matchingJoints = this._joints.filter(function (impostorJoint) {
  87769. return (impostorJoint.connectedImpostor === connectedImpostor
  87770. && impostorJoint.joint === joint
  87771. && impostorJoint.mainImpostor === mainImpostor);
  87772. });
  87773. if (matchingJoints.length) {
  87774. this._physicsPlugin.removeJoint(matchingJoints[0]);
  87775. //TODO remove it from the list as well
  87776. }
  87777. };
  87778. /**
  87779. * Called by the scene. no need to call it.
  87780. * @hidden
  87781. */
  87782. PhysicsEngine.prototype._step = function (delta) {
  87783. var _this = this;
  87784. //check if any mesh has no body / requires an update
  87785. this._impostors.forEach(function (impostor) {
  87786. if (impostor.isBodyInitRequired()) {
  87787. _this._physicsPlugin.generatePhysicsBody(impostor);
  87788. }
  87789. });
  87790. if (delta > 0.1) {
  87791. delta = 0.1;
  87792. }
  87793. else if (delta <= 0) {
  87794. delta = 1.0 / 60.0;
  87795. }
  87796. this._physicsPlugin.executeStep(delta, this._impostors);
  87797. };
  87798. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  87799. return this._physicsPlugin;
  87800. };
  87801. PhysicsEngine.prototype.getImpostors = function () {
  87802. return this._impostors;
  87803. };
  87804. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  87805. for (var i = 0; i < this._impostors.length; ++i) {
  87806. if (this._impostors[i].object === object) {
  87807. return this._impostors[i];
  87808. }
  87809. }
  87810. return null;
  87811. };
  87812. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  87813. for (var i = 0; i < this._impostors.length; ++i) {
  87814. if (this._impostors[i].physicsBody === body) {
  87815. return this._impostors[i];
  87816. }
  87817. }
  87818. return null;
  87819. };
  87820. // Statics
  87821. PhysicsEngine.Epsilon = 0.001;
  87822. return PhysicsEngine;
  87823. }());
  87824. BABYLON.PhysicsEngine = PhysicsEngine;
  87825. })(BABYLON || (BABYLON = {}));
  87826. //# sourceMappingURL=babylon.physicsEngine.js.map
  87827. var BABYLON;
  87828. (function (BABYLON) {
  87829. var PhysicsHelper = /** @class */ (function () {
  87830. function PhysicsHelper(scene) {
  87831. this._scene = scene;
  87832. this._physicsEngine = this._scene.getPhysicsEngine();
  87833. if (!this._physicsEngine) {
  87834. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  87835. }
  87836. }
  87837. /**
  87838. * @param {Vector3} origin the origin of the explosion
  87839. * @param {number} radius the explosion radius
  87840. * @param {number} strength the explosion strength
  87841. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  87842. */
  87843. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  87844. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87845. if (!this._physicsEngine) {
  87846. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  87847. return null;
  87848. }
  87849. var impostors = this._physicsEngine.getImpostors();
  87850. if (impostors.length === 0) {
  87851. return null;
  87852. }
  87853. var event = new PhysicsRadialExplosionEvent(this._scene);
  87854. impostors.forEach(function (impostor) {
  87855. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  87856. if (!impostorForceAndContactPoint) {
  87857. return;
  87858. }
  87859. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  87860. });
  87861. event.dispose(false);
  87862. return event;
  87863. };
  87864. /**
  87865. * @param {Vector3} origin the origin of the explosion
  87866. * @param {number} radius the explosion radius
  87867. * @param {number} strength the explosion strength
  87868. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  87869. */
  87870. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  87871. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87872. if (!this._physicsEngine) {
  87873. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87874. return null;
  87875. }
  87876. var impostors = this._physicsEngine.getImpostors();
  87877. if (impostors.length === 0) {
  87878. return null;
  87879. }
  87880. var event = new PhysicsRadialExplosionEvent(this._scene);
  87881. impostors.forEach(function (impostor) {
  87882. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  87883. if (!impostorForceAndContactPoint) {
  87884. return;
  87885. }
  87886. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  87887. });
  87888. event.dispose(false);
  87889. return event;
  87890. };
  87891. /**
  87892. * @param {Vector3} origin the origin of the explosion
  87893. * @param {number} radius the explosion radius
  87894. * @param {number} strength the explosion strength
  87895. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  87896. */
  87897. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  87898. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87899. if (!this._physicsEngine) {
  87900. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87901. return null;
  87902. }
  87903. var impostors = this._physicsEngine.getImpostors();
  87904. if (impostors.length === 0) {
  87905. return null;
  87906. }
  87907. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  87908. event.dispose(false);
  87909. return event;
  87910. };
  87911. /**
  87912. * @param {Vector3} origin the origin of the updraft
  87913. * @param {number} radius the radius of the updraft
  87914. * @param {number} strength the strength of the updraft
  87915. * @param {number} height the height of the updraft
  87916. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  87917. */
  87918. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  87919. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  87920. if (!this._physicsEngine) {
  87921. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87922. return null;
  87923. }
  87924. if (this._physicsEngine.getImpostors().length === 0) {
  87925. return null;
  87926. }
  87927. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  87928. event.dispose(false);
  87929. return event;
  87930. };
  87931. /**
  87932. * @param {Vector3} origin the of the vortex
  87933. * @param {number} radius the radius of the vortex
  87934. * @param {number} strength the strength of the vortex
  87935. * @param {number} height the height of the vortex
  87936. */
  87937. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  87938. if (!this._physicsEngine) {
  87939. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87940. return null;
  87941. }
  87942. if (this._physicsEngine.getImpostors().length === 0) {
  87943. return null;
  87944. }
  87945. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  87946. event.dispose(false);
  87947. return event;
  87948. };
  87949. return PhysicsHelper;
  87950. }());
  87951. BABYLON.PhysicsHelper = PhysicsHelper;
  87952. /***** Radial explosion *****/
  87953. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  87954. function PhysicsRadialExplosionEvent(scene) {
  87955. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  87956. this._rays = [];
  87957. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  87958. this._scene = scene;
  87959. }
  87960. /**
  87961. * Returns the data related to the radial explosion event (sphere & rays).
  87962. * @returns {PhysicsRadialExplosionEventData}
  87963. */
  87964. PhysicsRadialExplosionEvent.prototype.getData = function () {
  87965. this._dataFetched = true;
  87966. return {
  87967. sphere: this._sphere,
  87968. rays: this._rays,
  87969. };
  87970. };
  87971. /**
  87972. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  87973. * @param impostor
  87974. * @param {Vector3} origin the origin of the explosion
  87975. * @param {number} radius the explosion radius
  87976. * @param {number} strength the explosion strength
  87977. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  87978. * @returns {Nullable<PhysicsForceAndContactPoint>}
  87979. */
  87980. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  87981. if (impostor.mass === 0) {
  87982. return null;
  87983. }
  87984. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  87985. return null;
  87986. }
  87987. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  87988. return null;
  87989. }
  87990. var impostorObjectCenter = impostor.getObjectCenter();
  87991. var direction = impostorObjectCenter.subtract(origin);
  87992. var ray = new BABYLON.Ray(origin, direction, radius);
  87993. this._rays.push(ray);
  87994. var hit = ray.intersectsMesh(impostor.object);
  87995. var contactPoint = hit.pickedPoint;
  87996. if (!contactPoint) {
  87997. return null;
  87998. }
  87999. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  88000. if (distanceFromOrigin > radius) {
  88001. return null;
  88002. }
  88003. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  88004. ? strength
  88005. : strength * (1 - (distanceFromOrigin / radius));
  88006. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  88007. return { force: force, contactPoint: contactPoint };
  88008. };
  88009. /**
  88010. * Disposes the sphere.
  88011. * @param {bolean} force
  88012. */
  88013. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  88014. var _this = this;
  88015. if (force === void 0) { force = true; }
  88016. if (force) {
  88017. this._sphere.dispose();
  88018. }
  88019. else {
  88020. setTimeout(function () {
  88021. if (!_this._dataFetched) {
  88022. _this._sphere.dispose();
  88023. }
  88024. }, 0);
  88025. }
  88026. };
  88027. /*** Helpers ***/
  88028. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  88029. if (!this._sphere) {
  88030. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  88031. this._sphere.isVisible = false;
  88032. }
  88033. };
  88034. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  88035. var impostorObject = impostor.object;
  88036. this._prepareSphere();
  88037. this._sphere.position = origin;
  88038. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  88039. this._sphere._updateBoundingInfo();
  88040. this._sphere.computeWorldMatrix(true);
  88041. return this._sphere.intersectsMesh(impostorObject, true);
  88042. };
  88043. return PhysicsRadialExplosionEvent;
  88044. }());
  88045. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  88046. /***** Gravitational Field *****/
  88047. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  88048. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  88049. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  88050. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  88051. this._physicsHelper = physicsHelper;
  88052. this._scene = scene;
  88053. this._origin = origin;
  88054. this._radius = radius;
  88055. this._strength = strength;
  88056. this._falloff = falloff;
  88057. this._tickCallback = this._tick.bind(this);
  88058. }
  88059. /**
  88060. * Returns the data related to the gravitational field event (sphere).
  88061. * @returns {PhysicsGravitationalFieldEventData}
  88062. */
  88063. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  88064. this._dataFetched = true;
  88065. return {
  88066. sphere: this._sphere,
  88067. };
  88068. };
  88069. /**
  88070. * Enables the gravitational field.
  88071. */
  88072. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  88073. this._tickCallback.call(this);
  88074. this._scene.registerBeforeRender(this._tickCallback);
  88075. };
  88076. /**
  88077. * Disables the gravitational field.
  88078. */
  88079. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  88080. this._scene.unregisterBeforeRender(this._tickCallback);
  88081. };
  88082. /**
  88083. * Disposes the sphere.
  88084. * @param {bolean} force
  88085. */
  88086. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  88087. var _this = this;
  88088. if (force === void 0) { force = true; }
  88089. if (force) {
  88090. this._sphere.dispose();
  88091. }
  88092. else {
  88093. setTimeout(function () {
  88094. if (!_this._dataFetched) {
  88095. _this._sphere.dispose();
  88096. }
  88097. }, 0);
  88098. }
  88099. };
  88100. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  88101. // Since the params won't change, we fetch the event only once
  88102. if (this._sphere) {
  88103. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  88104. }
  88105. else {
  88106. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  88107. if (radialExplosionEvent) {
  88108. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  88109. }
  88110. }
  88111. };
  88112. return PhysicsGravitationalFieldEvent;
  88113. }());
  88114. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  88115. /***** Updraft *****/
  88116. var PhysicsUpdraftEvent = /** @class */ (function () {
  88117. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  88118. this._scene = _scene;
  88119. this._origin = _origin;
  88120. this._radius = _radius;
  88121. this._strength = _strength;
  88122. this._height = _height;
  88123. this._updraftMode = _updraftMode;
  88124. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  88125. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  88126. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  88127. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  88128. this._physicsEngine = this._scene.getPhysicsEngine();
  88129. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  88130. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  88131. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  88132. this._originDirection = this._origin.subtract(this._originTop).normalize();
  88133. }
  88134. this._tickCallback = this._tick.bind(this);
  88135. }
  88136. /**
  88137. * Returns the data related to the updraft event (cylinder).
  88138. * @returns {PhysicsUpdraftEventData}
  88139. */
  88140. PhysicsUpdraftEvent.prototype.getData = function () {
  88141. this._dataFetched = true;
  88142. return {
  88143. cylinder: this._cylinder,
  88144. };
  88145. };
  88146. /**
  88147. * Enables the updraft.
  88148. */
  88149. PhysicsUpdraftEvent.prototype.enable = function () {
  88150. this._tickCallback.call(this);
  88151. this._scene.registerBeforeRender(this._tickCallback);
  88152. };
  88153. /**
  88154. * Disables the cortex.
  88155. */
  88156. PhysicsUpdraftEvent.prototype.disable = function () {
  88157. this._scene.unregisterBeforeRender(this._tickCallback);
  88158. };
  88159. /**
  88160. * Disposes the sphere.
  88161. * @param {bolean} force
  88162. */
  88163. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  88164. var _this = this;
  88165. if (force === void 0) { force = true; }
  88166. if (force) {
  88167. this._cylinder.dispose();
  88168. }
  88169. else {
  88170. setTimeout(function () {
  88171. if (!_this._dataFetched) {
  88172. _this._cylinder.dispose();
  88173. }
  88174. }, 0);
  88175. }
  88176. };
  88177. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  88178. if (impostor.mass === 0) {
  88179. return null;
  88180. }
  88181. if (!this._intersectsWithCylinder(impostor)) {
  88182. return null;
  88183. }
  88184. var impostorObjectCenter = impostor.getObjectCenter();
  88185. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  88186. var direction = this._originDirection;
  88187. }
  88188. else {
  88189. var direction = impostorObjectCenter.subtract(this._originTop);
  88190. }
  88191. var multiplier = this._strength * -1;
  88192. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  88193. return { force: force, contactPoint: impostorObjectCenter };
  88194. };
  88195. PhysicsUpdraftEvent.prototype._tick = function () {
  88196. var _this = this;
  88197. this._physicsEngine.getImpostors().forEach(function (impostor) {
  88198. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  88199. if (!impostorForceAndContactPoint) {
  88200. return;
  88201. }
  88202. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  88203. });
  88204. };
  88205. /*** Helpers ***/
  88206. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  88207. if (!this._cylinder) {
  88208. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  88209. height: this._height,
  88210. diameter: this._radius * 2,
  88211. }, this._scene);
  88212. this._cylinder.isVisible = false;
  88213. }
  88214. };
  88215. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  88216. var impostorObject = impostor.object;
  88217. this._prepareCylinder();
  88218. this._cylinder.position = this._cylinderPosition;
  88219. return this._cylinder.intersectsMesh(impostorObject, true);
  88220. };
  88221. return PhysicsUpdraftEvent;
  88222. }());
  88223. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  88224. /***** Vortex *****/
  88225. var PhysicsVortexEvent = /** @class */ (function () {
  88226. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  88227. this._scene = _scene;
  88228. this._origin = _origin;
  88229. this._radius = _radius;
  88230. this._strength = _strength;
  88231. this._height = _height;
  88232. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  88233. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  88234. this._updraftMultiplier = 0.02;
  88235. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  88236. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  88237. this._physicsEngine = this._scene.getPhysicsEngine();
  88238. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  88239. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  88240. this._tickCallback = this._tick.bind(this);
  88241. }
  88242. /**
  88243. * Returns the data related to the vortex event (cylinder).
  88244. * @returns {PhysicsVortexEventData}
  88245. */
  88246. PhysicsVortexEvent.prototype.getData = function () {
  88247. this._dataFetched = true;
  88248. return {
  88249. cylinder: this._cylinder,
  88250. };
  88251. };
  88252. /**
  88253. * Enables the vortex.
  88254. */
  88255. PhysicsVortexEvent.prototype.enable = function () {
  88256. this._tickCallback.call(this);
  88257. this._scene.registerBeforeRender(this._tickCallback);
  88258. };
  88259. /**
  88260. * Disables the cortex.
  88261. */
  88262. PhysicsVortexEvent.prototype.disable = function () {
  88263. this._scene.unregisterBeforeRender(this._tickCallback);
  88264. };
  88265. /**
  88266. * Disposes the sphere.
  88267. * @param {bolean} force
  88268. */
  88269. PhysicsVortexEvent.prototype.dispose = function (force) {
  88270. var _this = this;
  88271. if (force === void 0) { force = true; }
  88272. if (force) {
  88273. this._cylinder.dispose();
  88274. }
  88275. else {
  88276. setTimeout(function () {
  88277. if (!_this._dataFetched) {
  88278. _this._cylinder.dispose();
  88279. }
  88280. }, 0);
  88281. }
  88282. };
  88283. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  88284. if (impostor.mass === 0) {
  88285. return null;
  88286. }
  88287. if (!this._intersectsWithCylinder(impostor)) {
  88288. return null;
  88289. }
  88290. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  88291. return null;
  88292. }
  88293. var impostorObjectCenter = impostor.getObjectCenter();
  88294. 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)
  88295. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  88296. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  88297. var hit = ray.intersectsMesh(impostor.object);
  88298. var contactPoint = hit.pickedPoint;
  88299. if (!contactPoint) {
  88300. return null;
  88301. }
  88302. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  88303. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  88304. var directionToOrigin = contactPoint.normalize();
  88305. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  88306. directionToOrigin = directionToOrigin.negate();
  88307. }
  88308. // TODO: find a more physically based solution
  88309. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  88310. var forceX = directionToOrigin.x * this._strength / 8;
  88311. var forceY = directionToOrigin.y * this._updraftMultiplier;
  88312. var forceZ = directionToOrigin.z * this._strength / 8;
  88313. }
  88314. else {
  88315. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  88316. var forceY = this._originTop.y * this._updraftMultiplier;
  88317. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  88318. }
  88319. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  88320. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  88321. return { force: force, contactPoint: impostorObjectCenter };
  88322. };
  88323. PhysicsVortexEvent.prototype._tick = function () {
  88324. var _this = this;
  88325. this._physicsEngine.getImpostors().forEach(function (impostor) {
  88326. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  88327. if (!impostorForceAndContactPoint) {
  88328. return;
  88329. }
  88330. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  88331. });
  88332. };
  88333. /*** Helpers ***/
  88334. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  88335. if (!this._cylinder) {
  88336. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  88337. height: this._height,
  88338. diameter: this._radius * 2,
  88339. }, this._scene);
  88340. this._cylinder.isVisible = false;
  88341. }
  88342. };
  88343. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  88344. var impostorObject = impostor.object;
  88345. this._prepareCylinder();
  88346. this._cylinder.position = this._cylinderPosition;
  88347. return this._cylinder.intersectsMesh(impostorObject, true);
  88348. };
  88349. return PhysicsVortexEvent;
  88350. }());
  88351. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  88352. /***** Enums *****/
  88353. /**
  88354. * The strenght of the force in correspondence to the distance of the affected object
  88355. */
  88356. var PhysicsRadialImpulseFalloff;
  88357. (function (PhysicsRadialImpulseFalloff) {
  88358. /** Defines that impulse is constant in strength across it's whole radius */
  88359. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  88360. /** DEfines that impulse gets weaker if it's further from the origin */
  88361. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  88362. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  88363. /**
  88364. * The strenght of the force in correspondence to the distance of the affected object
  88365. */
  88366. var PhysicsUpdraftMode;
  88367. (function (PhysicsUpdraftMode) {
  88368. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  88369. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  88370. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  88371. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  88372. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  88373. })(BABYLON || (BABYLON = {}));
  88374. //# sourceMappingURL=babylon.physicsHelper.js.map
  88375. var BABYLON;
  88376. (function (BABYLON) {
  88377. var CannonJSPlugin = /** @class */ (function () {
  88378. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  88379. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  88380. if (iterations === void 0) { iterations = 10; }
  88381. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  88382. this.name = "CannonJSPlugin";
  88383. this._physicsMaterials = new Array();
  88384. this._fixedTimeStep = 1 / 60;
  88385. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  88386. this.BJSCANNON = CANNON;
  88387. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  88388. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  88389. this._tmpPosition = BABYLON.Vector3.Zero();
  88390. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  88391. this._tmpUnityRotation = new BABYLON.Quaternion();
  88392. if (!this.isSupported()) {
  88393. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  88394. return;
  88395. }
  88396. this._extendNamespace();
  88397. this.world = new this.BJSCANNON.World();
  88398. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  88399. this.world.solver.iterations = iterations;
  88400. }
  88401. CannonJSPlugin.prototype.setGravity = function (gravity) {
  88402. this.world.gravity.copy(gravity);
  88403. };
  88404. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  88405. this._fixedTimeStep = timeStep;
  88406. };
  88407. CannonJSPlugin.prototype.getTimeStep = function () {
  88408. return this._fixedTimeStep;
  88409. };
  88410. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  88411. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  88412. };
  88413. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  88414. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  88415. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  88416. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  88417. };
  88418. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  88419. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  88420. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  88421. impostor.physicsBody.applyForce(impulse, worldPoint);
  88422. };
  88423. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  88424. //parent-child relationship. Does this impostor has a parent impostor?
  88425. if (impostor.parent) {
  88426. if (impostor.physicsBody) {
  88427. this.removePhysicsBody(impostor);
  88428. //TODO is that needed?
  88429. impostor.forceUpdate();
  88430. }
  88431. return;
  88432. }
  88433. //should a new body be created for this impostor?
  88434. if (impostor.isBodyInitRequired()) {
  88435. var shape = this._createShape(impostor);
  88436. //unregister events, if body is being changed
  88437. var oldBody = impostor.physicsBody;
  88438. if (oldBody) {
  88439. this.removePhysicsBody(impostor);
  88440. }
  88441. //create the body and material
  88442. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  88443. var bodyCreationObject = {
  88444. mass: impostor.getParam("mass"),
  88445. material: material
  88446. };
  88447. // A simple extend, in case native options were used.
  88448. var nativeOptions = impostor.getParam("nativeOptions");
  88449. for (var key in nativeOptions) {
  88450. if (nativeOptions.hasOwnProperty(key)) {
  88451. bodyCreationObject[key] = nativeOptions[key];
  88452. }
  88453. }
  88454. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  88455. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  88456. this.world.addEventListener("preStep", impostor.beforeStep);
  88457. this.world.addEventListener("postStep", impostor.afterStep);
  88458. impostor.physicsBody.addShape(shape);
  88459. this.world.add(impostor.physicsBody);
  88460. //try to keep the body moving in the right direction by taking old properties.
  88461. //Should be tested!
  88462. if (oldBody) {
  88463. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  88464. impostor.physicsBody[param].copy(oldBody[param]);
  88465. });
  88466. }
  88467. this._processChildMeshes(impostor);
  88468. }
  88469. //now update the body's transformation
  88470. this._updatePhysicsBodyTransformation(impostor);
  88471. };
  88472. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  88473. var _this = this;
  88474. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  88475. var currentRotation = mainImpostor.object.rotationQuaternion;
  88476. if (meshChildren.length) {
  88477. var processMesh = function (localPosition, mesh) {
  88478. if (!currentRotation || !mesh.rotationQuaternion) {
  88479. return;
  88480. }
  88481. var childImpostor = mesh.getPhysicsImpostor();
  88482. if (childImpostor) {
  88483. var parent = childImpostor.parent;
  88484. if (parent !== mainImpostor) {
  88485. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  88486. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  88487. if (childImpostor.physicsBody) {
  88488. _this.removePhysicsBody(childImpostor);
  88489. childImpostor.physicsBody = null;
  88490. }
  88491. childImpostor.parent = mainImpostor;
  88492. childImpostor.resetUpdateFlags();
  88493. 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));
  88494. //Add the mass of the children.
  88495. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  88496. }
  88497. }
  88498. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  88499. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  88500. };
  88501. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  88502. }
  88503. };
  88504. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  88505. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  88506. this.world.removeEventListener("preStep", impostor.beforeStep);
  88507. this.world.removeEventListener("postStep", impostor.afterStep);
  88508. this.world.remove(impostor.physicsBody);
  88509. };
  88510. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  88511. var mainBody = impostorJoint.mainImpostor.physicsBody;
  88512. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  88513. if (!mainBody || !connectedBody) {
  88514. return;
  88515. }
  88516. var constraint;
  88517. var jointData = impostorJoint.joint.jointData;
  88518. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  88519. var constraintData = {
  88520. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  88521. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  88522. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  88523. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  88524. maxForce: jointData.nativeParams.maxForce,
  88525. collideConnected: !!jointData.collision
  88526. };
  88527. switch (impostorJoint.joint.type) {
  88528. case BABYLON.PhysicsJoint.HingeJoint:
  88529. case BABYLON.PhysicsJoint.Hinge2Joint:
  88530. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  88531. break;
  88532. case BABYLON.PhysicsJoint.DistanceJoint:
  88533. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  88534. break;
  88535. case BABYLON.PhysicsJoint.SpringJoint:
  88536. var springData = jointData;
  88537. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  88538. restLength: springData.length,
  88539. stiffness: springData.stiffness,
  88540. damping: springData.damping,
  88541. localAnchorA: constraintData.pivotA,
  88542. localAnchorB: constraintData.pivotB
  88543. });
  88544. break;
  88545. case BABYLON.PhysicsJoint.LockJoint:
  88546. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  88547. break;
  88548. case BABYLON.PhysicsJoint.PointToPointJoint:
  88549. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  88550. default:
  88551. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  88552. break;
  88553. }
  88554. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  88555. constraint.collideConnected = !!jointData.collision;
  88556. impostorJoint.joint.physicsJoint = constraint;
  88557. //don't add spring as constraint, as it is not one.
  88558. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  88559. this.world.addConstraint(constraint);
  88560. }
  88561. else {
  88562. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  88563. constraint.applyForce();
  88564. });
  88565. }
  88566. };
  88567. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  88568. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  88569. };
  88570. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  88571. var index;
  88572. var mat;
  88573. for (index = 0; index < this._physicsMaterials.length; index++) {
  88574. mat = this._physicsMaterials[index];
  88575. if (mat.friction === friction && mat.restitution === restitution) {
  88576. return mat;
  88577. }
  88578. }
  88579. var currentMat = new this.BJSCANNON.Material(name);
  88580. currentMat.friction = friction;
  88581. currentMat.restitution = restitution;
  88582. this._physicsMaterials.push(currentMat);
  88583. return currentMat;
  88584. };
  88585. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  88586. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  88587. };
  88588. CannonJSPlugin.prototype._createShape = function (impostor) {
  88589. var object = impostor.object;
  88590. var returnValue;
  88591. var extendSize = impostor.getObjectExtendSize();
  88592. switch (impostor.type) {
  88593. case BABYLON.PhysicsImpostor.SphereImpostor:
  88594. var radiusX = extendSize.x;
  88595. var radiusY = extendSize.y;
  88596. var radiusZ = extendSize.z;
  88597. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  88598. break;
  88599. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  88600. case BABYLON.PhysicsImpostor.CylinderImpostor:
  88601. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  88602. break;
  88603. case BABYLON.PhysicsImpostor.BoxImpostor:
  88604. var box = extendSize.scale(0.5);
  88605. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  88606. break;
  88607. case BABYLON.PhysicsImpostor.PlaneImpostor:
  88608. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  88609. returnValue = new this.BJSCANNON.Plane();
  88610. break;
  88611. case BABYLON.PhysicsImpostor.MeshImpostor:
  88612. // should transform the vertex data to world coordinates!!
  88613. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  88614. var rawFaces = object.getIndices ? object.getIndices() : [];
  88615. if (!rawVerts)
  88616. return;
  88617. // get only scale! so the object could transform correctly.
  88618. var oldPosition = object.position.clone();
  88619. var oldRotation = object.rotation && object.rotation.clone();
  88620. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  88621. object.position.copyFromFloats(0, 0, 0);
  88622. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  88623. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  88624. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  88625. var transform = object.computeWorldMatrix(true);
  88626. // convert rawVerts to object space
  88627. var temp = new Array();
  88628. var index;
  88629. for (index = 0; index < rawVerts.length; index += 3) {
  88630. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  88631. }
  88632. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  88633. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  88634. //now set back the transformation!
  88635. object.position.copyFrom(oldPosition);
  88636. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  88637. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  88638. break;
  88639. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  88640. var oldPosition2 = object.position.clone();
  88641. var oldRotation2 = object.rotation && object.rotation.clone();
  88642. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  88643. object.position.copyFromFloats(0, 0, 0);
  88644. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  88645. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  88646. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  88647. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  88648. returnValue = this._createHeightmap(object);
  88649. object.position.copyFrom(oldPosition2);
  88650. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  88651. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  88652. object.computeWorldMatrix(true);
  88653. break;
  88654. case BABYLON.PhysicsImpostor.ParticleImpostor:
  88655. returnValue = new this.BJSCANNON.Particle();
  88656. break;
  88657. }
  88658. return returnValue;
  88659. };
  88660. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  88661. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  88662. var transform = object.computeWorldMatrix(true);
  88663. // convert rawVerts to object space
  88664. var temp = new Array();
  88665. var index;
  88666. for (index = 0; index < pos.length; index += 3) {
  88667. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  88668. }
  88669. pos = temp;
  88670. var matrix = new Array();
  88671. //For now pointDepth will not be used and will be automatically calculated.
  88672. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  88673. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  88674. var boundingInfo = object.getBoundingInfo();
  88675. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  88676. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  88677. var elementSize = dim * 2 / arraySize;
  88678. for (var i = 0; i < pos.length; i = i + 3) {
  88679. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  88680. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  88681. var y = -pos[i + 2] + minY;
  88682. if (!matrix[x]) {
  88683. matrix[x] = [];
  88684. }
  88685. if (!matrix[x][z]) {
  88686. matrix[x][z] = y;
  88687. }
  88688. matrix[x][z] = Math.max(y, matrix[x][z]);
  88689. }
  88690. for (var x = 0; x <= arraySize; ++x) {
  88691. if (!matrix[x]) {
  88692. var loc = 1;
  88693. while (!matrix[(x + loc) % arraySize]) {
  88694. loc++;
  88695. }
  88696. matrix[x] = matrix[(x + loc) % arraySize].slice();
  88697. //console.log("missing x", x);
  88698. }
  88699. for (var z = 0; z <= arraySize; ++z) {
  88700. if (!matrix[x][z]) {
  88701. var loc = 1;
  88702. var newValue;
  88703. while (newValue === undefined) {
  88704. newValue = matrix[x][(z + loc++) % arraySize];
  88705. }
  88706. matrix[x][z] = newValue;
  88707. }
  88708. }
  88709. }
  88710. var shape = new this.BJSCANNON.Heightfield(matrix, {
  88711. elementSize: elementSize
  88712. });
  88713. //For future reference, needed for body transformation
  88714. shape.minY = minY;
  88715. return shape;
  88716. };
  88717. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  88718. var object = impostor.object;
  88719. //make sure it is updated...
  88720. object.computeWorldMatrix && object.computeWorldMatrix(true);
  88721. // The delta between the mesh position and the mesh bounding box center
  88722. var bInfo = object.getBoundingInfo();
  88723. if (!bInfo)
  88724. return;
  88725. var center = impostor.getObjectCenter();
  88726. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  88727. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  88728. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  88729. this._tmpPosition.copyFrom(center);
  88730. var quaternion = object.rotationQuaternion;
  88731. if (!quaternion) {
  88732. return;
  88733. }
  88734. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  88735. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  88736. //-90 DEG in X, precalculated
  88737. quaternion = quaternion.multiply(this._minus90X);
  88738. //Invert! (Precalculated, 90 deg in X)
  88739. //No need to clone. this will never change.
  88740. impostor.setDeltaRotation(this._plus90X);
  88741. }
  88742. //If it is a heightfield, if should be centered.
  88743. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  88744. var mesh = object;
  88745. var boundingInfo = mesh.getBoundingInfo();
  88746. //calculate the correct body position:
  88747. var rotationQuaternion = mesh.rotationQuaternion;
  88748. mesh.rotationQuaternion = this._tmpUnityRotation;
  88749. mesh.computeWorldMatrix(true);
  88750. //get original center with no rotation
  88751. var c = center.clone();
  88752. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  88753. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  88754. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  88755. mesh.setPreTransformMatrix(p);
  88756. mesh.computeWorldMatrix(true);
  88757. //calculate the translation
  88758. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  88759. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  88760. //add it inverted to the delta
  88761. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  88762. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  88763. //rotation is back
  88764. mesh.rotationQuaternion = rotationQuaternion;
  88765. mesh.setPreTransformMatrix(oldPivot);
  88766. mesh.computeWorldMatrix(true);
  88767. }
  88768. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  88769. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  88770. //this._tmpPosition.copyFrom(object.position);
  88771. }
  88772. impostor.setDeltaPosition(this._tmpDeltaPosition);
  88773. //Now update the impostor object
  88774. impostor.physicsBody.position.copy(this._tmpPosition);
  88775. impostor.physicsBody.quaternion.copy(quaternion);
  88776. };
  88777. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  88778. impostor.object.position.copyFrom(impostor.physicsBody.position);
  88779. if (impostor.object.rotationQuaternion) {
  88780. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  88781. }
  88782. };
  88783. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  88784. impostor.physicsBody.position.copy(newPosition);
  88785. impostor.physicsBody.quaternion.copy(newRotation);
  88786. };
  88787. CannonJSPlugin.prototype.isSupported = function () {
  88788. return this.BJSCANNON !== undefined;
  88789. };
  88790. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  88791. impostor.physicsBody.velocity.copy(velocity);
  88792. };
  88793. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  88794. impostor.physicsBody.angularVelocity.copy(velocity);
  88795. };
  88796. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  88797. var v = impostor.physicsBody.velocity;
  88798. if (!v) {
  88799. return null;
  88800. }
  88801. return new BABYLON.Vector3(v.x, v.y, v.z);
  88802. };
  88803. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  88804. var v = impostor.physicsBody.angularVelocity;
  88805. if (!v) {
  88806. return null;
  88807. }
  88808. return new BABYLON.Vector3(v.x, v.y, v.z);
  88809. };
  88810. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  88811. impostor.physicsBody.mass = mass;
  88812. impostor.physicsBody.updateMassProperties();
  88813. };
  88814. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  88815. return impostor.physicsBody.mass;
  88816. };
  88817. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  88818. return impostor.physicsBody.material.friction;
  88819. };
  88820. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  88821. impostor.physicsBody.material.friction = friction;
  88822. };
  88823. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  88824. return impostor.physicsBody.material.restitution;
  88825. };
  88826. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  88827. impostor.physicsBody.material.restitution = restitution;
  88828. };
  88829. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  88830. impostor.physicsBody.sleep();
  88831. };
  88832. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  88833. impostor.physicsBody.wakeUp();
  88834. };
  88835. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  88836. joint.physicsJoint.distance = maxDistance;
  88837. };
  88838. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  88839. // if (!motorIndex) {
  88840. // joint.physicsJoint.enableMotor();
  88841. // }
  88842. // }
  88843. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  88844. // if (!motorIndex) {
  88845. // joint.physicsJoint.disableMotor();
  88846. // }
  88847. // }
  88848. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  88849. if (!motorIndex) {
  88850. joint.physicsJoint.enableMotor();
  88851. joint.physicsJoint.setMotorSpeed(speed);
  88852. if (maxForce) {
  88853. this.setLimit(joint, maxForce);
  88854. }
  88855. }
  88856. };
  88857. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  88858. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  88859. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  88860. };
  88861. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  88862. var body = impostor.physicsBody;
  88863. mesh.position.x = body.position.x;
  88864. mesh.position.y = body.position.y;
  88865. mesh.position.z = body.position.z;
  88866. if (mesh.rotationQuaternion) {
  88867. mesh.rotationQuaternion.x = body.quaternion.x;
  88868. mesh.rotationQuaternion.y = body.quaternion.y;
  88869. mesh.rotationQuaternion.z = body.quaternion.z;
  88870. mesh.rotationQuaternion.w = body.quaternion.w;
  88871. }
  88872. };
  88873. CannonJSPlugin.prototype.getRadius = function (impostor) {
  88874. var shape = impostor.physicsBody.shapes[0];
  88875. return shape.boundingSphereRadius;
  88876. };
  88877. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  88878. var shape = impostor.physicsBody.shapes[0];
  88879. result.x = shape.halfExtents.x * 2;
  88880. result.y = shape.halfExtents.y * 2;
  88881. result.z = shape.halfExtents.z * 2;
  88882. };
  88883. CannonJSPlugin.prototype.dispose = function () {
  88884. };
  88885. CannonJSPlugin.prototype._extendNamespace = function () {
  88886. //this will force cannon to execute at least one step when using interpolation
  88887. var step_tmp1 = new this.BJSCANNON.Vec3();
  88888. var Engine = this.BJSCANNON;
  88889. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  88890. maxSubSteps = maxSubSteps || 10;
  88891. timeSinceLastCalled = timeSinceLastCalled || 0;
  88892. if (timeSinceLastCalled === 0) {
  88893. this.internalStep(dt);
  88894. this.time += dt;
  88895. }
  88896. else {
  88897. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  88898. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  88899. var t0 = performance.now();
  88900. for (var i = 0; i !== internalSteps; i++) {
  88901. this.internalStep(dt);
  88902. if (performance.now() - t0 > dt * 1000) {
  88903. break;
  88904. }
  88905. }
  88906. this.time += timeSinceLastCalled;
  88907. var h = this.time % dt;
  88908. var h_div_dt = h / dt;
  88909. var interpvelo = step_tmp1;
  88910. var bodies = this.bodies;
  88911. for (var j = 0; j !== bodies.length; j++) {
  88912. var b = bodies[j];
  88913. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  88914. b.position.vsub(b.previousPosition, interpvelo);
  88915. interpvelo.scale(h_div_dt, interpvelo);
  88916. b.position.vadd(interpvelo, b.interpolatedPosition);
  88917. }
  88918. else {
  88919. b.interpolatedPosition.copy(b.position);
  88920. b.interpolatedQuaternion.copy(b.quaternion);
  88921. }
  88922. }
  88923. }
  88924. };
  88925. };
  88926. return CannonJSPlugin;
  88927. }());
  88928. BABYLON.CannonJSPlugin = CannonJSPlugin;
  88929. })(BABYLON || (BABYLON = {}));
  88930. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  88931. var BABYLON;
  88932. (function (BABYLON) {
  88933. var OimoJSPlugin = /** @class */ (function () {
  88934. function OimoJSPlugin(iterations) {
  88935. this.name = "OimoJSPlugin";
  88936. this._tmpImpostorsArray = [];
  88937. this._tmpPositionVector = BABYLON.Vector3.Zero();
  88938. this.BJSOIMO = OIMO;
  88939. this.world = new this.BJSOIMO.World({
  88940. iterations: iterations
  88941. });
  88942. this.world.clear();
  88943. }
  88944. OimoJSPlugin.prototype.setGravity = function (gravity) {
  88945. this.world.gravity.copy(gravity);
  88946. };
  88947. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  88948. this.world.timeStep = timeStep;
  88949. };
  88950. OimoJSPlugin.prototype.getTimeStep = function () {
  88951. return this.world.timeStep;
  88952. };
  88953. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  88954. var _this = this;
  88955. impostors.forEach(function (impostor) {
  88956. impostor.beforeStep();
  88957. });
  88958. this.world.step();
  88959. impostors.forEach(function (impostor) {
  88960. impostor.afterStep();
  88961. //update the ordered impostors array
  88962. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  88963. });
  88964. //check for collisions
  88965. var contact = this.world.contacts;
  88966. while (contact !== null) {
  88967. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  88968. contact = contact.next;
  88969. continue;
  88970. }
  88971. //is this body colliding with any other? get the impostor
  88972. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  88973. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  88974. if (!mainImpostor || !collidingImpostor) {
  88975. contact = contact.next;
  88976. continue;
  88977. }
  88978. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  88979. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  88980. contact = contact.next;
  88981. }
  88982. };
  88983. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  88984. var mass = impostor.physicsBody.mass;
  88985. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  88986. };
  88987. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  88988. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  88989. this.applyImpulse(impostor, force, contactPoint);
  88990. };
  88991. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  88992. var _this = this;
  88993. //parent-child relationship. Does this impostor has a parent impostor?
  88994. if (impostor.parent) {
  88995. if (impostor.physicsBody) {
  88996. this.removePhysicsBody(impostor);
  88997. //TODO is that needed?
  88998. impostor.forceUpdate();
  88999. }
  89000. return;
  89001. }
  89002. if (impostor.isBodyInitRequired()) {
  89003. var bodyConfig = {
  89004. name: impostor.uniqueId,
  89005. //Oimo must have mass, also for static objects.
  89006. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  89007. size: [],
  89008. type: [],
  89009. pos: [],
  89010. posShape: [],
  89011. rot: [],
  89012. rotShape: [],
  89013. move: impostor.getParam("mass") !== 0,
  89014. density: impostor.getParam("mass"),
  89015. friction: impostor.getParam("friction"),
  89016. restitution: impostor.getParam("restitution"),
  89017. //Supporting older versions of Oimo
  89018. world: this.world
  89019. };
  89020. var impostors = [impostor];
  89021. var addToArray = function (parent) {
  89022. if (!parent.getChildMeshes)
  89023. return;
  89024. parent.getChildMeshes().forEach(function (m) {
  89025. if (m.physicsImpostor) {
  89026. impostors.push(m.physicsImpostor);
  89027. //m.physicsImpostor._init();
  89028. }
  89029. });
  89030. };
  89031. addToArray(impostor.object);
  89032. var checkWithEpsilon_1 = function (value) {
  89033. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  89034. };
  89035. var globalQuaternion_1 = new BABYLON.Quaternion();
  89036. impostors.forEach(function (i) {
  89037. if (!i.object.rotationQuaternion) {
  89038. return;
  89039. }
  89040. //get the correct bounding box
  89041. var oldQuaternion = i.object.rotationQuaternion;
  89042. globalQuaternion_1 = oldQuaternion.clone();
  89043. var rot = oldQuaternion.toEulerAngles();
  89044. var extendSize = i.getObjectExtendSize();
  89045. var radToDeg = 57.295779513082320876;
  89046. if (i === impostor) {
  89047. var center = impostor.getObjectCenter();
  89048. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  89049. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  89050. //Can also use Array.prototype.push.apply
  89051. bodyConfig.pos.push(center.x);
  89052. bodyConfig.pos.push(center.y);
  89053. bodyConfig.pos.push(center.z);
  89054. bodyConfig.posShape.push(0, 0, 0);
  89055. //tmp solution
  89056. bodyConfig.rot.push(0);
  89057. bodyConfig.rot.push(0);
  89058. bodyConfig.rot.push(0);
  89059. bodyConfig.rotShape.push(0, 0, 0);
  89060. }
  89061. else {
  89062. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  89063. bodyConfig.posShape.push(localPosition.x);
  89064. bodyConfig.posShape.push(localPosition.y);
  89065. bodyConfig.posShape.push(localPosition.z);
  89066. bodyConfig.pos.push(0, 0, 0);
  89067. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  89068. bodyConfig.rot.push(0);
  89069. bodyConfig.rot.push(0);
  89070. bodyConfig.rot.push(0);
  89071. bodyConfig.rotShape.push(rot.x * radToDeg);
  89072. bodyConfig.rotShape.push(rot.y * radToDeg);
  89073. bodyConfig.rotShape.push(rot.z * radToDeg);
  89074. }
  89075. // register mesh
  89076. switch (i.type) {
  89077. case BABYLON.PhysicsImpostor.ParticleImpostor:
  89078. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  89079. case BABYLON.PhysicsImpostor.SphereImpostor:
  89080. var radiusX = extendSize.x;
  89081. var radiusY = extendSize.y;
  89082. var radiusZ = extendSize.z;
  89083. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  89084. bodyConfig.type.push('sphere');
  89085. //due to the way oimo works with compounds, add 3 times
  89086. bodyConfig.size.push(size);
  89087. bodyConfig.size.push(size);
  89088. bodyConfig.size.push(size);
  89089. break;
  89090. case BABYLON.PhysicsImpostor.CylinderImpostor:
  89091. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  89092. var sizeY = checkWithEpsilon_1(extendSize.y);
  89093. bodyConfig.type.push('cylinder');
  89094. bodyConfig.size.push(sizeX);
  89095. bodyConfig.size.push(sizeY);
  89096. //due to the way oimo works with compounds, add one more value.
  89097. bodyConfig.size.push(sizeY);
  89098. break;
  89099. case BABYLON.PhysicsImpostor.PlaneImpostor:
  89100. case BABYLON.PhysicsImpostor.BoxImpostor:
  89101. default:
  89102. var sizeX = checkWithEpsilon_1(extendSize.x);
  89103. var sizeY = checkWithEpsilon_1(extendSize.y);
  89104. var sizeZ = checkWithEpsilon_1(extendSize.z);
  89105. bodyConfig.type.push('box');
  89106. //if (i === impostor) {
  89107. bodyConfig.size.push(sizeX);
  89108. bodyConfig.size.push(sizeY);
  89109. bodyConfig.size.push(sizeZ);
  89110. //} else {
  89111. // bodyConfig.size.push(0,0,0);
  89112. //}
  89113. break;
  89114. }
  89115. //actually not needed, but hey...
  89116. i.object.rotationQuaternion = oldQuaternion;
  89117. });
  89118. impostor.physicsBody = this.world.add(bodyConfig);
  89119. // set the quaternion, ignoring the previously defined (euler) rotation
  89120. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  89121. // update with delta 0, so the body will reveive the new rotation.
  89122. impostor.physicsBody.updatePosition(0);
  89123. }
  89124. else {
  89125. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  89126. }
  89127. impostor.setDeltaPosition(this._tmpPositionVector);
  89128. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  89129. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  89130. };
  89131. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  89132. //impostor.physicsBody.dispose();
  89133. //Same as : (older oimo versions)
  89134. this.world.removeRigidBody(impostor.physicsBody);
  89135. };
  89136. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  89137. var mainBody = impostorJoint.mainImpostor.physicsBody;
  89138. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  89139. if (!mainBody || !connectedBody) {
  89140. return;
  89141. }
  89142. var jointData = impostorJoint.joint.jointData;
  89143. var options = jointData.nativeParams || {};
  89144. var type;
  89145. var nativeJointData = {
  89146. body1: mainBody,
  89147. body2: connectedBody,
  89148. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  89149. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  89150. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  89151. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  89152. min: options.min,
  89153. max: options.max,
  89154. collision: options.collision || jointData.collision,
  89155. spring: options.spring,
  89156. //supporting older version of Oimo
  89157. world: this.world
  89158. };
  89159. switch (impostorJoint.joint.type) {
  89160. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  89161. type = "jointBall";
  89162. break;
  89163. case BABYLON.PhysicsJoint.SpringJoint:
  89164. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  89165. var springData = jointData;
  89166. nativeJointData.min = springData.length || nativeJointData.min;
  89167. //Max should also be set, just make sure it is at least min
  89168. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  89169. case BABYLON.PhysicsJoint.DistanceJoint:
  89170. type = "jointDistance";
  89171. nativeJointData.max = jointData.maxDistance;
  89172. break;
  89173. case BABYLON.PhysicsJoint.PrismaticJoint:
  89174. type = "jointPrisme";
  89175. break;
  89176. case BABYLON.PhysicsJoint.SliderJoint:
  89177. type = "jointSlide";
  89178. break;
  89179. case BABYLON.PhysicsJoint.WheelJoint:
  89180. type = "jointWheel";
  89181. break;
  89182. case BABYLON.PhysicsJoint.HingeJoint:
  89183. default:
  89184. type = "jointHinge";
  89185. break;
  89186. }
  89187. nativeJointData.type = type;
  89188. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  89189. };
  89190. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  89191. //Bug in Oimo prevents us from disposing a joint in the playground
  89192. //joint.joint.physicsJoint.dispose();
  89193. //So we will bruteforce it!
  89194. try {
  89195. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  89196. }
  89197. catch (e) {
  89198. BABYLON.Tools.Warn(e);
  89199. }
  89200. };
  89201. OimoJSPlugin.prototype.isSupported = function () {
  89202. return this.BJSOIMO !== undefined;
  89203. };
  89204. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  89205. if (!impostor.physicsBody.sleeping) {
  89206. //TODO check that
  89207. /*if (impostor.physicsBody.shapes.next) {
  89208. var parentShape = this._getLastShape(impostor.physicsBody);
  89209. impostor.object.position.copyFrom(parentShape.position);
  89210. console.log(parentShape.position);
  89211. } else {*/
  89212. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  89213. //}
  89214. if (impostor.object.rotationQuaternion) {
  89215. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  89216. }
  89217. }
  89218. };
  89219. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  89220. var body = impostor.physicsBody;
  89221. body.position.copy(newPosition);
  89222. body.orientation.copy(newRotation);
  89223. body.syncShapes();
  89224. body.awake();
  89225. };
  89226. /*private _getLastShape(body: any): any {
  89227. var lastShape = body.shapes;
  89228. while (lastShape.next) {
  89229. lastShape = lastShape.next;
  89230. }
  89231. return lastShape;
  89232. }*/
  89233. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  89234. impostor.physicsBody.linearVelocity.copy(velocity);
  89235. };
  89236. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  89237. impostor.physicsBody.angularVelocity.copy(velocity);
  89238. };
  89239. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  89240. var v = impostor.physicsBody.linearVelocity;
  89241. if (!v) {
  89242. return null;
  89243. }
  89244. return new BABYLON.Vector3(v.x, v.y, v.z);
  89245. };
  89246. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  89247. var v = impostor.physicsBody.angularVelocity;
  89248. if (!v) {
  89249. return null;
  89250. }
  89251. return new BABYLON.Vector3(v.x, v.y, v.z);
  89252. };
  89253. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  89254. var staticBody = mass === 0;
  89255. //this will actually set the body's density and not its mass.
  89256. //But this is how oimo treats the mass variable.
  89257. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  89258. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  89259. };
  89260. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  89261. return impostor.physicsBody.shapes.density;
  89262. };
  89263. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  89264. return impostor.physicsBody.shapes.friction;
  89265. };
  89266. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  89267. impostor.physicsBody.shapes.friction = friction;
  89268. };
  89269. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  89270. return impostor.physicsBody.shapes.restitution;
  89271. };
  89272. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  89273. impostor.physicsBody.shapes.restitution = restitution;
  89274. };
  89275. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  89276. impostor.physicsBody.sleep();
  89277. };
  89278. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  89279. impostor.physicsBody.awake();
  89280. };
  89281. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  89282. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  89283. if (minDistance !== void 0) {
  89284. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  89285. }
  89286. };
  89287. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  89288. //TODO separate rotational and transational motors.
  89289. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  89290. if (motor) {
  89291. motor.setMotor(speed, maxForce);
  89292. }
  89293. };
  89294. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  89295. //TODO separate rotational and transational motors.
  89296. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  89297. if (motor) {
  89298. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  89299. }
  89300. };
  89301. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  89302. var body = impostor.physicsBody;
  89303. mesh.position.x = body.position.x;
  89304. mesh.position.y = body.position.y;
  89305. mesh.position.z = body.position.z;
  89306. if (mesh.rotationQuaternion) {
  89307. mesh.rotationQuaternion.x = body.orientation.x;
  89308. mesh.rotationQuaternion.y = body.orientation.y;
  89309. mesh.rotationQuaternion.z = body.orientation.z;
  89310. mesh.rotationQuaternion.w = body.orientation.s;
  89311. }
  89312. };
  89313. OimoJSPlugin.prototype.getRadius = function (impostor) {
  89314. return impostor.physicsBody.shapes.radius;
  89315. };
  89316. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  89317. var shape = impostor.physicsBody.shapes;
  89318. result.x = shape.halfWidth * 2;
  89319. result.y = shape.halfHeight * 2;
  89320. result.z = shape.halfDepth * 2;
  89321. };
  89322. OimoJSPlugin.prototype.dispose = function () {
  89323. this.world.clear();
  89324. };
  89325. return OimoJSPlugin;
  89326. }());
  89327. BABYLON.OimoJSPlugin = OimoJSPlugin;
  89328. })(BABYLON || (BABYLON = {}));
  89329. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  89330. var BABYLON;
  89331. (function (BABYLON) {
  89332. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  89333. // All values and structures referenced from:
  89334. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  89335. var DDS_MAGIC = 0x20534444;
  89336. var
  89337. //DDSD_CAPS = 0x1,
  89338. //DDSD_HEIGHT = 0x2,
  89339. //DDSD_WIDTH = 0x4,
  89340. //DDSD_PITCH = 0x8,
  89341. //DDSD_PIXELFORMAT = 0x1000,
  89342. DDSD_MIPMAPCOUNT = 0x20000;
  89343. //DDSD_LINEARSIZE = 0x80000,
  89344. //DDSD_DEPTH = 0x800000;
  89345. // var DDSCAPS_COMPLEX = 0x8,
  89346. // DDSCAPS_MIPMAP = 0x400000,
  89347. // DDSCAPS_TEXTURE = 0x1000;
  89348. var DDSCAPS2_CUBEMAP = 0x200;
  89349. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  89350. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  89351. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  89352. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  89353. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  89354. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  89355. // DDSCAPS2_VOLUME = 0x200000;
  89356. var
  89357. //DDPF_ALPHAPIXELS = 0x1,
  89358. //DDPF_ALPHA = 0x2,
  89359. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  89360. //DDPF_YUV = 0x200,
  89361. DDPF_LUMINANCE = 0x20000;
  89362. function FourCCToInt32(value) {
  89363. return value.charCodeAt(0) +
  89364. (value.charCodeAt(1) << 8) +
  89365. (value.charCodeAt(2) << 16) +
  89366. (value.charCodeAt(3) << 24);
  89367. }
  89368. function Int32ToFourCC(value) {
  89369. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  89370. }
  89371. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  89372. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  89373. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  89374. var FOURCC_DX10 = FourCCToInt32("DX10");
  89375. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  89376. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  89377. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  89378. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  89379. var headerLengthInt = 31; // The header length in 32 bit ints
  89380. // Offsets into the header array
  89381. var off_magic = 0;
  89382. var off_size = 1;
  89383. var off_flags = 2;
  89384. var off_height = 3;
  89385. var off_width = 4;
  89386. var off_mipmapCount = 7;
  89387. var off_pfFlags = 20;
  89388. var off_pfFourCC = 21;
  89389. var off_RGBbpp = 22;
  89390. var off_RMask = 23;
  89391. var off_GMask = 24;
  89392. var off_BMask = 25;
  89393. var off_AMask = 26;
  89394. // var off_caps1 = 27;
  89395. var off_caps2 = 28;
  89396. // var off_caps3 = 29;
  89397. // var off_caps4 = 30;
  89398. var off_dxgiFormat = 32;
  89399. ;
  89400. var DDSTools = /** @class */ (function () {
  89401. function DDSTools() {
  89402. }
  89403. DDSTools.GetDDSInfo = function (arrayBuffer) {
  89404. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  89405. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  89406. var mipmapCount = 1;
  89407. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  89408. mipmapCount = Math.max(1, header[off_mipmapCount]);
  89409. }
  89410. var fourCC = header[off_pfFourCC];
  89411. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  89412. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89413. switch (fourCC) {
  89414. case FOURCC_D3DFMT_R16G16B16A16F:
  89415. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89416. break;
  89417. case FOURCC_D3DFMT_R32G32B32A32F:
  89418. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89419. break;
  89420. case FOURCC_DX10:
  89421. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  89422. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89423. break;
  89424. }
  89425. }
  89426. return {
  89427. width: header[off_width],
  89428. height: header[off_height],
  89429. mipmapCount: mipmapCount,
  89430. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  89431. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  89432. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  89433. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  89434. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  89435. dxgiFormat: dxgiFormat,
  89436. textureType: textureType
  89437. };
  89438. };
  89439. DDSTools._ToHalfFloat = function (value) {
  89440. if (!DDSTools._FloatView) {
  89441. DDSTools._FloatView = new Float32Array(1);
  89442. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  89443. }
  89444. DDSTools._FloatView[0] = value;
  89445. var x = DDSTools._Int32View[0];
  89446. var bits = (x >> 16) & 0x8000; /* Get the sign */
  89447. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  89448. var e = (x >> 23) & 0xff; /* Using int is faster here */
  89449. /* If zero, or denormal, or exponent underflows too much for a denormal
  89450. * half, return signed zero. */
  89451. if (e < 103) {
  89452. return bits;
  89453. }
  89454. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  89455. if (e > 142) {
  89456. bits |= 0x7c00;
  89457. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  89458. * not Inf, so make sure we set one mantissa bit too. */
  89459. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  89460. return bits;
  89461. }
  89462. /* If exponent underflows but not too much, return a denormal */
  89463. if (e < 113) {
  89464. m |= 0x0800;
  89465. /* Extra rounding may overflow and set mantissa to 0 and exponent
  89466. * to 1, which is OK. */
  89467. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  89468. return bits;
  89469. }
  89470. bits |= ((e - 112) << 10) | (m >> 1);
  89471. bits += m & 1;
  89472. return bits;
  89473. };
  89474. DDSTools._FromHalfFloat = function (value) {
  89475. var s = (value & 0x8000) >> 15;
  89476. var e = (value & 0x7C00) >> 10;
  89477. var f = value & 0x03FF;
  89478. if (e === 0) {
  89479. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  89480. }
  89481. else if (e == 0x1F) {
  89482. return f ? NaN : ((s ? -1 : 1) * Infinity);
  89483. }
  89484. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  89485. };
  89486. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89487. var destArray = new Float32Array(dataLength);
  89488. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  89489. var index = 0;
  89490. for (var y = 0; y < height; y++) {
  89491. for (var x = 0; x < width; x++) {
  89492. var srcPos = (x + y * width) * 4;
  89493. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  89494. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  89495. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  89496. if (DDSTools.StoreLODInAlphaChannel) {
  89497. destArray[index + 3] = lod;
  89498. }
  89499. else {
  89500. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  89501. }
  89502. index += 4;
  89503. }
  89504. }
  89505. return destArray;
  89506. };
  89507. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89508. if (DDSTools.StoreLODInAlphaChannel) {
  89509. var destArray = new Uint16Array(dataLength);
  89510. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  89511. var index = 0;
  89512. for (var y = 0; y < height; y++) {
  89513. for (var x = 0; x < width; x++) {
  89514. var srcPos = (x + y * width) * 4;
  89515. destArray[index] = srcData[srcPos];
  89516. destArray[index + 1] = srcData[srcPos + 1];
  89517. destArray[index + 2] = srcData[srcPos + 2];
  89518. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  89519. index += 4;
  89520. }
  89521. }
  89522. return destArray;
  89523. }
  89524. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  89525. };
  89526. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89527. if (DDSTools.StoreLODInAlphaChannel) {
  89528. var destArray = new Float32Array(dataLength);
  89529. var srcData = new Float32Array(arrayBuffer, dataOffset);
  89530. var index = 0;
  89531. for (var y = 0; y < height; y++) {
  89532. for (var x = 0; x < width; x++) {
  89533. var srcPos = (x + y * width) * 4;
  89534. destArray[index] = srcData[srcPos];
  89535. destArray[index + 1] = srcData[srcPos + 1];
  89536. destArray[index + 2] = srcData[srcPos + 2];
  89537. destArray[index + 3] = lod;
  89538. index += 4;
  89539. }
  89540. }
  89541. return destArray;
  89542. }
  89543. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  89544. };
  89545. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89546. var destArray = new Uint8Array(dataLength);
  89547. var srcData = new Float32Array(arrayBuffer, dataOffset);
  89548. var index = 0;
  89549. for (var y = 0; y < height; y++) {
  89550. for (var x = 0; x < width; x++) {
  89551. var srcPos = (x + y * width) * 4;
  89552. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  89553. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  89554. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  89555. if (DDSTools.StoreLODInAlphaChannel) {
  89556. destArray[index + 3] = lod;
  89557. }
  89558. else {
  89559. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  89560. }
  89561. index += 4;
  89562. }
  89563. }
  89564. return destArray;
  89565. };
  89566. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89567. var destArray = new Uint8Array(dataLength);
  89568. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  89569. var index = 0;
  89570. for (var y = 0; y < height; y++) {
  89571. for (var x = 0; x < width; x++) {
  89572. var srcPos = (x + y * width) * 4;
  89573. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  89574. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  89575. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  89576. if (DDSTools.StoreLODInAlphaChannel) {
  89577. destArray[index + 3] = lod;
  89578. }
  89579. else {
  89580. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  89581. }
  89582. index += 4;
  89583. }
  89584. }
  89585. return destArray;
  89586. };
  89587. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  89588. var byteArray = new Uint8Array(dataLength);
  89589. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  89590. var index = 0;
  89591. for (var y = 0; y < height; y++) {
  89592. for (var x = 0; x < width; x++) {
  89593. var srcPos = (x + y * width) * 4;
  89594. byteArray[index] = srcData[srcPos + rOffset];
  89595. byteArray[index + 1] = srcData[srcPos + gOffset];
  89596. byteArray[index + 2] = srcData[srcPos + bOffset];
  89597. byteArray[index + 3] = srcData[srcPos + aOffset];
  89598. index += 4;
  89599. }
  89600. }
  89601. return byteArray;
  89602. };
  89603. DDSTools._ExtractLongWordOrder = function (value) {
  89604. if (value === 0 || value === 255 || value === -16777216) {
  89605. return 0;
  89606. }
  89607. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  89608. };
  89609. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  89610. var byteArray = new Uint8Array(dataLength);
  89611. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  89612. var index = 0;
  89613. for (var y = 0; y < height; y++) {
  89614. for (var x = 0; x < width; x++) {
  89615. var srcPos = (x + y * width) * 3;
  89616. byteArray[index] = srcData[srcPos + rOffset];
  89617. byteArray[index + 1] = srcData[srcPos + gOffset];
  89618. byteArray[index + 2] = srcData[srcPos + bOffset];
  89619. index += 3;
  89620. }
  89621. }
  89622. return byteArray;
  89623. };
  89624. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  89625. var byteArray = new Uint8Array(dataLength);
  89626. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  89627. var index = 0;
  89628. for (var y = 0; y < height; y++) {
  89629. for (var x = 0; x < width; x++) {
  89630. var srcPos = (x + y * width);
  89631. byteArray[index] = srcData[srcPos];
  89632. index++;
  89633. }
  89634. }
  89635. return byteArray;
  89636. };
  89637. /**
  89638. * Uploads DDS Levels to a Babylon Texture
  89639. * @hidden
  89640. */
  89641. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  89642. if (lodIndex === void 0) { lodIndex = -1; }
  89643. var sphericalPolynomialFaces = null;
  89644. if (info.sphericalPolynomial) {
  89645. sphericalPolynomialFaces = new Array();
  89646. }
  89647. var ext = engine.getCaps().s3tc;
  89648. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  89649. var fourCC, width, height, dataLength = 0, dataOffset;
  89650. var byteArray, mipmapCount, mip;
  89651. var internalCompressedFormat = 0;
  89652. var blockBytes = 1;
  89653. if (header[off_magic] !== DDS_MAGIC) {
  89654. BABYLON.Tools.Error("Invalid magic number in DDS header");
  89655. return;
  89656. }
  89657. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  89658. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  89659. return;
  89660. }
  89661. if (info.isCompressed && !ext) {
  89662. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  89663. return;
  89664. }
  89665. var bpp = header[off_RGBbpp];
  89666. dataOffset = header[off_size] + 4;
  89667. var computeFormats = false;
  89668. if (info.isFourCC) {
  89669. fourCC = header[off_pfFourCC];
  89670. switch (fourCC) {
  89671. case FOURCC_DXT1:
  89672. blockBytes = 8;
  89673. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  89674. break;
  89675. case FOURCC_DXT3:
  89676. blockBytes = 16;
  89677. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  89678. break;
  89679. case FOURCC_DXT5:
  89680. blockBytes = 16;
  89681. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  89682. break;
  89683. case FOURCC_D3DFMT_R16G16B16A16F:
  89684. computeFormats = true;
  89685. break;
  89686. case FOURCC_D3DFMT_R32G32B32A32F:
  89687. computeFormats = true;
  89688. break;
  89689. case FOURCC_DX10:
  89690. // There is an additionnal header so dataOffset need to be changed
  89691. dataOffset += 5 * 4; // 5 uints
  89692. var supported = false;
  89693. switch (info.dxgiFormat) {
  89694. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  89695. computeFormats = true;
  89696. supported = true;
  89697. break;
  89698. case DXGI_FORMAT_B8G8R8X8_UNORM:
  89699. info.isRGB = true;
  89700. info.isFourCC = false;
  89701. bpp = 32;
  89702. supported = true;
  89703. break;
  89704. }
  89705. if (supported) {
  89706. break;
  89707. }
  89708. default:
  89709. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  89710. return;
  89711. }
  89712. }
  89713. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  89714. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  89715. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  89716. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  89717. if (computeFormats) {
  89718. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  89719. }
  89720. mipmapCount = 1;
  89721. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  89722. mipmapCount = Math.max(1, header[off_mipmapCount]);
  89723. }
  89724. for (var face = 0; face < faces; face++) {
  89725. width = header[off_width];
  89726. height = header[off_height];
  89727. for (mip = 0; mip < mipmapCount; ++mip) {
  89728. if (lodIndex === -1 || lodIndex === mip) {
  89729. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  89730. var i = (lodIndex === -1) ? mip : 0;
  89731. if (!info.isCompressed && info.isFourCC) {
  89732. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  89733. dataLength = width * height * 4;
  89734. var floatArray = null;
  89735. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  89736. if (bpp === 128) {
  89737. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89738. if (sphericalPolynomialFaces && i == 0) {
  89739. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  89740. }
  89741. }
  89742. else if (bpp === 64) {
  89743. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89744. if (sphericalPolynomialFaces && i == 0) {
  89745. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  89746. }
  89747. }
  89748. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89749. }
  89750. else {
  89751. if (bpp === 128) {
  89752. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89753. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89754. if (sphericalPolynomialFaces && i == 0) {
  89755. sphericalPolynomialFaces.push(floatArray);
  89756. }
  89757. }
  89758. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  89759. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89760. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89761. if (sphericalPolynomialFaces && i == 0) {
  89762. sphericalPolynomialFaces.push(floatArray);
  89763. }
  89764. }
  89765. else { // 64
  89766. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89767. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89768. if (sphericalPolynomialFaces && i == 0) {
  89769. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  89770. }
  89771. }
  89772. }
  89773. if (floatArray) {
  89774. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  89775. }
  89776. }
  89777. else if (info.isRGB) {
  89778. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89779. if (bpp === 24) {
  89780. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  89781. dataLength = width * height * 3;
  89782. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  89783. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  89784. }
  89785. else { // 32
  89786. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  89787. dataLength = width * height * 4;
  89788. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  89789. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  89790. }
  89791. }
  89792. else if (info.isLuminance) {
  89793. var unpackAlignment = engine._getUnpackAlignement();
  89794. var unpaddedRowSize = width;
  89795. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  89796. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  89797. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  89798. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  89799. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89800. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  89801. }
  89802. else {
  89803. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  89804. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  89805. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89806. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  89807. }
  89808. }
  89809. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  89810. width *= 0.5;
  89811. height *= 0.5;
  89812. width = Math.max(1.0, width);
  89813. height = Math.max(1.0, height);
  89814. }
  89815. if (currentFace !== undefined) {
  89816. // Loading a single face
  89817. break;
  89818. }
  89819. }
  89820. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  89821. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  89822. size: header[off_width],
  89823. right: sphericalPolynomialFaces[0],
  89824. left: sphericalPolynomialFaces[1],
  89825. up: sphericalPolynomialFaces[2],
  89826. down: sphericalPolynomialFaces[3],
  89827. front: sphericalPolynomialFaces[4],
  89828. back: sphericalPolynomialFaces[5],
  89829. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  89830. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  89831. gammaSpace: false,
  89832. });
  89833. }
  89834. else {
  89835. info.sphericalPolynomial = undefined;
  89836. }
  89837. };
  89838. DDSTools.StoreLODInAlphaChannel = false;
  89839. return DDSTools;
  89840. }());
  89841. BABYLON.DDSTools = DDSTools;
  89842. })(BABYLON || (BABYLON = {}));
  89843. //# sourceMappingURL=babylon.dds.js.map
  89844. var BABYLON;
  89845. (function (BABYLON) {
  89846. /**
  89847. * Implementation of the DDS Texture Loader.
  89848. */
  89849. var DDSTextureLoader = /** @class */ (function () {
  89850. function DDSTextureLoader() {
  89851. /**
  89852. * Defines wether the loader supports cascade loading the different faces.
  89853. */
  89854. this.supportCascades = true;
  89855. }
  89856. /**
  89857. * This returns if the loader support the current file information.
  89858. * @param extension defines the file extension of the file being loaded
  89859. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89860. * @param fallback defines the fallback internal texture if any
  89861. * @param isBase64 defines whether the texture is encoded as a base64
  89862. * @param isBuffer defines whether the texture data are stored as a buffer
  89863. * @returns true if the loader can load the specified file
  89864. */
  89865. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  89866. return extension.indexOf(".dds") === 0;
  89867. };
  89868. /**
  89869. * Transform the url before loading if required.
  89870. * @param rootUrl the url of the texture
  89871. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89872. * @returns the transformed texture
  89873. */
  89874. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  89875. return rootUrl;
  89876. };
  89877. /**
  89878. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  89879. * @param rootUrl the url of the texture
  89880. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89881. * @returns the fallback texture
  89882. */
  89883. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  89884. return null;
  89885. };
  89886. /**
  89887. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  89888. * @param data contains the texture data
  89889. * @param texture defines the BabylonJS internal texture
  89890. * @param createPolynomials will be true if polynomials have been requested
  89891. * @param onLoad defines the callback to trigger once the texture is ready
  89892. * @param onError defines the callback to trigger in case of error
  89893. */
  89894. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  89895. var engine = texture.getEngine();
  89896. var info;
  89897. var loadMipmap = false;
  89898. if (Array.isArray(imgs)) {
  89899. for (var index = 0; index < imgs.length; index++) {
  89900. var data_1 = imgs[index];
  89901. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  89902. texture.width = info.width;
  89903. texture.height = info.height;
  89904. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  89905. engine._unpackFlipY(info.isCompressed);
  89906. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  89907. if (!info.isFourCC && info.mipmapCount === 1) {
  89908. engine.generateMipMapsForCubemap(texture);
  89909. }
  89910. }
  89911. }
  89912. else {
  89913. var data = imgs;
  89914. info = BABYLON.DDSTools.GetDDSInfo(data);
  89915. texture.width = info.width;
  89916. texture.height = info.height;
  89917. if (createPolynomials) {
  89918. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  89919. }
  89920. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  89921. engine._unpackFlipY(info.isCompressed);
  89922. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  89923. if (!info.isFourCC && info.mipmapCount === 1) {
  89924. engine.generateMipMapsForCubemap(texture);
  89925. }
  89926. }
  89927. engine._setCubeMapTextureParams(loadMipmap);
  89928. texture.isReady = true;
  89929. if (onLoad) {
  89930. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  89931. }
  89932. };
  89933. /**
  89934. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  89935. * @param data contains the texture data
  89936. * @param texture defines the BabylonJS internal texture
  89937. * @param callback defines the method to call once ready to upload
  89938. */
  89939. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  89940. var info = BABYLON.DDSTools.GetDDSInfo(data);
  89941. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  89942. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  89943. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  89944. });
  89945. };
  89946. return DDSTextureLoader;
  89947. }());
  89948. // Register the loader.
  89949. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  89950. })(BABYLON || (BABYLON = {}));
  89951. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  89952. var BABYLON;
  89953. (function (BABYLON) {
  89954. /*
  89955. * Based on jsTGALoader - Javascript loader for TGA file
  89956. * By Vincent Thibault
  89957. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  89958. */
  89959. var TGATools = /** @class */ (function () {
  89960. function TGATools() {
  89961. }
  89962. TGATools.GetTGAHeader = function (data) {
  89963. var offset = 0;
  89964. var header = {
  89965. id_length: data[offset++],
  89966. colormap_type: data[offset++],
  89967. image_type: data[offset++],
  89968. colormap_index: data[offset++] | data[offset++] << 8,
  89969. colormap_length: data[offset++] | data[offset++] << 8,
  89970. colormap_size: data[offset++],
  89971. origin: [
  89972. data[offset++] | data[offset++] << 8,
  89973. data[offset++] | data[offset++] << 8
  89974. ],
  89975. width: data[offset++] | data[offset++] << 8,
  89976. height: data[offset++] | data[offset++] << 8,
  89977. pixel_size: data[offset++],
  89978. flags: data[offset++]
  89979. };
  89980. return header;
  89981. };
  89982. /**
  89983. * Uploads TGA content to a Babylon Texture
  89984. * @hidden
  89985. */
  89986. TGATools.UploadContent = function (texture, data) {
  89987. // Not enough data to contain header ?
  89988. if (data.length < 19) {
  89989. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  89990. return;
  89991. }
  89992. // Read Header
  89993. var offset = 18;
  89994. var header = TGATools.GetTGAHeader(data);
  89995. // Assume it's a valid Targa file.
  89996. if (header.id_length + offset > data.length) {
  89997. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  89998. return;
  89999. }
  90000. // Skip not needed data
  90001. offset += header.id_length;
  90002. var use_rle = false;
  90003. var use_pal = false;
  90004. var use_grey = false;
  90005. // Get some informations.
  90006. switch (header.image_type) {
  90007. case TGATools._TYPE_RLE_INDEXED:
  90008. use_rle = true;
  90009. case TGATools._TYPE_INDEXED:
  90010. use_pal = true;
  90011. break;
  90012. case TGATools._TYPE_RLE_RGB:
  90013. use_rle = true;
  90014. case TGATools._TYPE_RGB:
  90015. // use_rgb = true;
  90016. break;
  90017. case TGATools._TYPE_RLE_GREY:
  90018. use_rle = true;
  90019. case TGATools._TYPE_GREY:
  90020. use_grey = true;
  90021. break;
  90022. }
  90023. var pixel_data;
  90024. // var numAlphaBits = header.flags & 0xf;
  90025. var pixel_size = header.pixel_size >> 3;
  90026. var pixel_total = header.width * header.height * pixel_size;
  90027. // Read palettes
  90028. var palettes;
  90029. if (use_pal) {
  90030. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  90031. }
  90032. // Read LRE
  90033. if (use_rle) {
  90034. pixel_data = new Uint8Array(pixel_total);
  90035. var c, count, i;
  90036. var localOffset = 0;
  90037. var pixels = new Uint8Array(pixel_size);
  90038. while (offset < pixel_total && localOffset < pixel_total) {
  90039. c = data[offset++];
  90040. count = (c & 0x7f) + 1;
  90041. // RLE pixels
  90042. if (c & 0x80) {
  90043. // Bind pixel tmp array
  90044. for (i = 0; i < pixel_size; ++i) {
  90045. pixels[i] = data[offset++];
  90046. }
  90047. // Copy pixel array
  90048. for (i = 0; i < count; ++i) {
  90049. pixel_data.set(pixels, localOffset + i * pixel_size);
  90050. }
  90051. localOffset += pixel_size * count;
  90052. }
  90053. // Raw pixels
  90054. else {
  90055. count *= pixel_size;
  90056. for (i = 0; i < count; ++i) {
  90057. pixel_data[localOffset + i] = data[offset++];
  90058. }
  90059. localOffset += count;
  90060. }
  90061. }
  90062. }
  90063. // RAW Pixels
  90064. else {
  90065. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  90066. }
  90067. // Load to texture
  90068. var x_start, y_start, x_step, y_step, y_end, x_end;
  90069. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  90070. default:
  90071. case TGATools._ORIGIN_UL:
  90072. x_start = 0;
  90073. x_step = 1;
  90074. x_end = header.width;
  90075. y_start = 0;
  90076. y_step = 1;
  90077. y_end = header.height;
  90078. break;
  90079. case TGATools._ORIGIN_BL:
  90080. x_start = 0;
  90081. x_step = 1;
  90082. x_end = header.width;
  90083. y_start = header.height - 1;
  90084. y_step = -1;
  90085. y_end = -1;
  90086. break;
  90087. case TGATools._ORIGIN_UR:
  90088. x_start = header.width - 1;
  90089. x_step = -1;
  90090. x_end = -1;
  90091. y_start = 0;
  90092. y_step = 1;
  90093. y_end = header.height;
  90094. break;
  90095. case TGATools._ORIGIN_BR:
  90096. x_start = header.width - 1;
  90097. x_step = -1;
  90098. x_end = -1;
  90099. y_start = header.height - 1;
  90100. y_step = -1;
  90101. y_end = -1;
  90102. break;
  90103. }
  90104. // Load the specify method
  90105. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  90106. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  90107. var engine = texture.getEngine();
  90108. engine._uploadDataToTextureDirectly(texture, imageData);
  90109. };
  90110. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  90111. var image = pixel_data, colormap = palettes;
  90112. var width = header.width, height = header.height;
  90113. var color, i = 0, x, y;
  90114. var imageData = new Uint8Array(width * height * 4);
  90115. for (y = y_start; y !== y_end; y += y_step) {
  90116. for (x = x_start; x !== x_end; x += x_step, i++) {
  90117. color = image[i];
  90118. imageData[(x + width * y) * 4 + 3] = 255;
  90119. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  90120. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  90121. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  90122. }
  90123. }
  90124. return imageData;
  90125. };
  90126. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  90127. var image = pixel_data;
  90128. var width = header.width, height = header.height;
  90129. var color, i = 0, x, y;
  90130. var imageData = new Uint8Array(width * height * 4);
  90131. for (y = y_start; y !== y_end; y += y_step) {
  90132. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  90133. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  90134. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  90135. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  90136. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  90137. imageData[(x + width * y) * 4 + 0] = r;
  90138. imageData[(x + width * y) * 4 + 1] = g;
  90139. imageData[(x + width * y) * 4 + 2] = b;
  90140. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  90141. }
  90142. }
  90143. return imageData;
  90144. };
  90145. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  90146. var image = pixel_data;
  90147. var width = header.width, height = header.height;
  90148. var i = 0, x, y;
  90149. var imageData = new Uint8Array(width * height * 4);
  90150. for (y = y_start; y !== y_end; y += y_step) {
  90151. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  90152. imageData[(x + width * y) * 4 + 3] = 255;
  90153. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  90154. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  90155. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  90156. }
  90157. }
  90158. return imageData;
  90159. };
  90160. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  90161. var image = pixel_data;
  90162. var width = header.width, height = header.height;
  90163. var i = 0, x, y;
  90164. var imageData = new Uint8Array(width * height * 4);
  90165. for (y = y_start; y !== y_end; y += y_step) {
  90166. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  90167. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  90168. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  90169. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  90170. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  90171. }
  90172. }
  90173. return imageData;
  90174. };
  90175. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  90176. var image = pixel_data;
  90177. var width = header.width, height = header.height;
  90178. var color, i = 0, x, y;
  90179. var imageData = new Uint8Array(width * height * 4);
  90180. for (y = y_start; y !== y_end; y += y_step) {
  90181. for (x = x_start; x !== x_end; x += x_step, i++) {
  90182. color = image[i];
  90183. imageData[(x + width * y) * 4 + 0] = color;
  90184. imageData[(x + width * y) * 4 + 1] = color;
  90185. imageData[(x + width * y) * 4 + 2] = color;
  90186. imageData[(x + width * y) * 4 + 3] = 255;
  90187. }
  90188. }
  90189. return imageData;
  90190. };
  90191. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  90192. var image = pixel_data;
  90193. var width = header.width, height = header.height;
  90194. var i = 0, x, y;
  90195. var imageData = new Uint8Array(width * height * 4);
  90196. for (y = y_start; y !== y_end; y += y_step) {
  90197. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  90198. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  90199. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  90200. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  90201. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  90202. }
  90203. }
  90204. return imageData;
  90205. };
  90206. //private static _TYPE_NO_DATA = 0;
  90207. TGATools._TYPE_INDEXED = 1;
  90208. TGATools._TYPE_RGB = 2;
  90209. TGATools._TYPE_GREY = 3;
  90210. TGATools._TYPE_RLE_INDEXED = 9;
  90211. TGATools._TYPE_RLE_RGB = 10;
  90212. TGATools._TYPE_RLE_GREY = 11;
  90213. TGATools._ORIGIN_MASK = 0x30;
  90214. TGATools._ORIGIN_SHIFT = 0x04;
  90215. TGATools._ORIGIN_BL = 0x00;
  90216. TGATools._ORIGIN_BR = 0x01;
  90217. TGATools._ORIGIN_UL = 0x02;
  90218. TGATools._ORIGIN_UR = 0x03;
  90219. return TGATools;
  90220. }());
  90221. BABYLON.TGATools = TGATools;
  90222. })(BABYLON || (BABYLON = {}));
  90223. //# sourceMappingURL=babylon.tga.js.map
  90224. var BABYLON;
  90225. (function (BABYLON) {
  90226. /**
  90227. * Implementation of the TGA Texture Loader.
  90228. */
  90229. var TGATextureLoader = /** @class */ (function () {
  90230. function TGATextureLoader() {
  90231. /**
  90232. * Defines wether the loader supports cascade loading the different faces.
  90233. */
  90234. this.supportCascades = false;
  90235. }
  90236. /**
  90237. * This returns if the loader support the current file information.
  90238. * @param extension defines the file extension of the file being loaded
  90239. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90240. * @param fallback defines the fallback internal texture if any
  90241. * @param isBase64 defines whether the texture is encoded as a base64
  90242. * @param isBuffer defines whether the texture data are stored as a buffer
  90243. * @returns true if the loader can load the specified file
  90244. */
  90245. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  90246. return extension.indexOf(".tga") === 0;
  90247. };
  90248. /**
  90249. * Transform the url before loading if required.
  90250. * @param rootUrl the url of the texture
  90251. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90252. * @returns the transformed texture
  90253. */
  90254. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  90255. return rootUrl;
  90256. };
  90257. /**
  90258. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  90259. * @param rootUrl the url of the texture
  90260. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90261. * @returns the fallback texture
  90262. */
  90263. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  90264. return null;
  90265. };
  90266. /**
  90267. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  90268. * @param data contains the texture data
  90269. * @param texture defines the BabylonJS internal texture
  90270. * @param createPolynomials will be true if polynomials have been requested
  90271. * @param onLoad defines the callback to trigger once the texture is ready
  90272. * @param onError defines the callback to trigger in case of error
  90273. */
  90274. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  90275. throw ".env not supported in Cube.";
  90276. };
  90277. /**
  90278. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  90279. * @param data contains the texture data
  90280. * @param texture defines the BabylonJS internal texture
  90281. * @param callback defines the method to call once ready to upload
  90282. */
  90283. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  90284. var uintData = new Uint8Array(data);
  90285. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  90286. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  90287. BABYLON.TGATools.UploadContent(texture, uintData);
  90288. });
  90289. };
  90290. return TGATextureLoader;
  90291. }());
  90292. // Register the loader.
  90293. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  90294. })(BABYLON || (BABYLON = {}));
  90295. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  90296. var BABYLON;
  90297. (function (BABYLON) {
  90298. /**
  90299. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  90300. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  90301. */
  90302. var KhronosTextureContainer = /** @class */ (function () {
  90303. /**
  90304. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  90305. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  90306. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  90307. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  90308. */
  90309. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  90310. this.arrayBuffer = arrayBuffer;
  90311. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  90312. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  90313. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  90314. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  90315. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  90316. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  90317. BABYLON.Tools.Error("texture missing KTX identifier");
  90318. return;
  90319. }
  90320. // load the reset of the header in native 32 bit int
  90321. var header = new Int32Array(this.arrayBuffer, 12, 13);
  90322. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  90323. var oppositeEndianess = header[0] === 0x01020304;
  90324. // read all the header elements in order they exist in the file, without modification (sans endainness)
  90325. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  90326. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  90327. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  90328. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  90329. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  90330. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  90331. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  90332. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  90333. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  90334. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  90335. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  90336. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  90337. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  90338. if (this.glType !== 0) {
  90339. BABYLON.Tools.Error("only compressed formats currently supported");
  90340. return;
  90341. }
  90342. else {
  90343. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  90344. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  90345. }
  90346. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  90347. BABYLON.Tools.Error("only 2D textures currently supported");
  90348. return;
  90349. }
  90350. if (this.numberOfArrayElements !== 0) {
  90351. BABYLON.Tools.Error("texture arrays not currently supported");
  90352. return;
  90353. }
  90354. if (this.numberOfFaces !== facesExpected) {
  90355. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  90356. return;
  90357. }
  90358. // we now have a completely validated file, so could use existence of loadType as success
  90359. // would need to make this more elaborate & adjust checks above to support more than one load type
  90360. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  90361. }
  90362. // not as fast hardware based, but will probably never need to use
  90363. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  90364. return ((val & 0xFF) << 24)
  90365. | ((val & 0xFF00) << 8)
  90366. | ((val >> 8) & 0xFF00)
  90367. | ((val >> 24) & 0xFF);
  90368. };
  90369. /**
  90370. * Uploads KTX content to a Babylon Texture.
  90371. * It is assumed that the texture has already been created & is currently bound
  90372. * @hidden
  90373. */
  90374. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  90375. switch (this.loadType) {
  90376. case KhronosTextureContainer.COMPRESSED_2D:
  90377. this._upload2DCompressedLevels(texture, loadMipmaps);
  90378. break;
  90379. case KhronosTextureContainer.TEX_2D:
  90380. case KhronosTextureContainer.COMPRESSED_3D:
  90381. case KhronosTextureContainer.TEX_3D:
  90382. }
  90383. };
  90384. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  90385. // initialize width & height for level 1
  90386. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  90387. var width = this.pixelWidth;
  90388. var height = this.pixelHeight;
  90389. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  90390. for (var level = 0; level < mipmapCount; level++) {
  90391. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  90392. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  90393. for (var face = 0; face < this.numberOfFaces; face++) {
  90394. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  90395. var engine = texture.getEngine();
  90396. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  90397. dataOffset += imageSize; // add size of the image for the next face/mipmap
  90398. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  90399. }
  90400. width = Math.max(1.0, width * 0.5);
  90401. height = Math.max(1.0, height * 0.5);
  90402. }
  90403. };
  90404. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  90405. // load types
  90406. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  90407. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  90408. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  90409. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  90410. return KhronosTextureContainer;
  90411. }());
  90412. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  90413. })(BABYLON || (BABYLON = {}));
  90414. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  90415. var BABYLON;
  90416. (function (BABYLON) {
  90417. /**
  90418. * Implementation of the KTX Texture Loader.
  90419. */
  90420. var KTXTextureLoader = /** @class */ (function () {
  90421. function KTXTextureLoader() {
  90422. /**
  90423. * Defines wether the loader supports cascade loading the different faces.
  90424. */
  90425. this.supportCascades = false;
  90426. }
  90427. /**
  90428. * This returns if the loader support the current file information.
  90429. * @param extension defines the file extension of the file being loaded
  90430. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90431. * @param fallback defines the fallback internal texture if any
  90432. * @param isBase64 defines whether the texture is encoded as a base64
  90433. * @param isBuffer defines whether the texture data are stored as a buffer
  90434. * @returns true if the loader can load the specified file
  90435. */
  90436. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  90437. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  90438. return true;
  90439. }
  90440. return false;
  90441. };
  90442. /**
  90443. * Transform the url before loading if required.
  90444. * @param rootUrl the url of the texture
  90445. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90446. * @returns the transformed texture
  90447. */
  90448. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  90449. var lastDot = rootUrl.lastIndexOf('.');
  90450. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  90451. };
  90452. /**
  90453. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  90454. * @param rootUrl the url of the texture
  90455. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90456. * @returns the fallback texture
  90457. */
  90458. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  90459. // remove the format appended to the rootUrl in the original createCubeTexture call.
  90460. var exp = new RegExp("" + textureFormatInUse + "$");
  90461. return rootUrl.replace(exp, "");
  90462. };
  90463. /**
  90464. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  90465. * @param data contains the texture data
  90466. * @param texture defines the BabylonJS internal texture
  90467. * @param createPolynomials will be true if polynomials have been requested
  90468. * @param onLoad defines the callback to trigger once the texture is ready
  90469. * @param onError defines the callback to trigger in case of error
  90470. */
  90471. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  90472. if (Array.isArray(data)) {
  90473. return;
  90474. }
  90475. var engine = texture.getEngine();
  90476. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  90477. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  90478. engine._unpackFlipY(true);
  90479. ktx.uploadLevels(texture, texture.generateMipMaps);
  90480. texture.width = ktx.pixelWidth;
  90481. texture.height = ktx.pixelHeight;
  90482. engine._setCubeMapTextureParams(loadMipmap);
  90483. texture.isReady = true;
  90484. };
  90485. /**
  90486. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  90487. * @param data contains the texture data
  90488. * @param texture defines the BabylonJS internal texture
  90489. * @param callback defines the method to call once ready to upload
  90490. */
  90491. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  90492. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  90493. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  90494. ktx.uploadLevels(texture, texture.generateMipMaps);
  90495. });
  90496. };
  90497. return KTXTextureLoader;
  90498. }());
  90499. // Register the loader.
  90500. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  90501. })(BABYLON || (BABYLON = {}));
  90502. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  90503. var BABYLON;
  90504. (function (BABYLON) {
  90505. /**
  90506. * Sets of helpers addressing the serialization and deserialization of environment texture
  90507. * stored in a BabylonJS env file.
  90508. * Those files are usually stored as .env files.
  90509. */
  90510. var EnvironmentTextureTools = /** @class */ (function () {
  90511. function EnvironmentTextureTools() {
  90512. }
  90513. /**
  90514. * Gets the environment info from an env file.
  90515. * @param data The array buffer containing the .env bytes.
  90516. * @returns the environment file info (the json header) if successfully parsed.
  90517. */
  90518. EnvironmentTextureTools.GetEnvInfo = function (data) {
  90519. var dataView = new DataView(data);
  90520. var pos = 0;
  90521. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  90522. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  90523. BABYLON.Tools.Error('Not a babylon environment map');
  90524. return null;
  90525. }
  90526. }
  90527. // Read json manifest - collect characters up to null terminator
  90528. var manifestString = '';
  90529. var charCode = 0x00;
  90530. while ((charCode = dataView.getUint8(pos++))) {
  90531. manifestString += String.fromCharCode(charCode);
  90532. }
  90533. var manifest = JSON.parse(manifestString);
  90534. if (manifest.specular) {
  90535. // Extend the header with the position of the payload.
  90536. manifest.specular.specularDataPosition = pos;
  90537. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  90538. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  90539. }
  90540. return manifest;
  90541. };
  90542. /**
  90543. * Creates an environment texture from a loaded cube texture.
  90544. * @param texture defines the cube texture to convert in env file
  90545. * @return a promise containing the environment data if succesfull.
  90546. */
  90547. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  90548. var _this = this;
  90549. var internalTexture = texture.getInternalTexture();
  90550. if (!internalTexture) {
  90551. return Promise.reject("The cube texture is invalid.");
  90552. }
  90553. if (!texture._prefiltered) {
  90554. return Promise.reject("The cube texture is invalid (not prefiltered).");
  90555. }
  90556. var engine = internalTexture.getEngine();
  90557. if (engine && engine.premultipliedAlpha) {
  90558. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  90559. }
  90560. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  90561. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  90562. }
  90563. var canvas = engine.getRenderingCanvas();
  90564. if (!canvas) {
  90565. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  90566. }
  90567. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90568. if (!engine.getCaps().textureFloatRender) {
  90569. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90570. if (!engine.getCaps().textureHalfFloatRender) {
  90571. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  90572. }
  90573. }
  90574. var cubeWidth = internalTexture.width;
  90575. var hostingScene = new BABYLON.Scene(engine);
  90576. var specularTextures = {};
  90577. var promises = [];
  90578. // Read and collect all mipmaps data from the cube.
  90579. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  90580. mipmapsCount = Math.round(mipmapsCount);
  90581. var _loop_1 = function (i) {
  90582. var faceWidth = Math.pow(2, mipmapsCount - i);
  90583. var _loop_2 = function (face) {
  90584. var data = texture.readPixels(face, i);
  90585. // Creates a temp texture with the face data.
  90586. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  90587. // And rgbdEncode them.
  90588. var promise = new Promise(function (resolve, reject) {
  90589. 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);
  90590. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  90591. rgbdPostProcess.onApply = function (effect) {
  90592. effect._bindTexture("textureSampler", tempTexture);
  90593. };
  90594. // As the process needs to happen on the main canvas, keep track of the current size
  90595. var currentW = engine.getRenderWidth();
  90596. var currentH = engine.getRenderHeight();
  90597. // Set the desired size for the texture
  90598. engine.setSize(faceWidth, faceWidth);
  90599. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  90600. // Reading datas from WebGL
  90601. BABYLON.Tools.ToBlob(canvas, function (blob) {
  90602. var fileReader = new FileReader();
  90603. fileReader.onload = function (event) {
  90604. var arrayBuffer = event.target.result;
  90605. specularTextures[i * 6 + face] = arrayBuffer;
  90606. resolve();
  90607. };
  90608. fileReader.readAsArrayBuffer(blob);
  90609. });
  90610. // Reapply the previous canvas size
  90611. engine.setSize(currentW, currentH);
  90612. });
  90613. });
  90614. promises.push(promise);
  90615. };
  90616. // All faces of the cube.
  90617. for (var face = 0; face < 6; face++) {
  90618. _loop_2(face);
  90619. }
  90620. };
  90621. for (var i = 0; i <= mipmapsCount; i++) {
  90622. _loop_1(i);
  90623. }
  90624. // Once all the textures haves been collected as RGBD stored in PNGs
  90625. return Promise.all(promises).then(function () {
  90626. // We can delete the hosting scene keeping track of all the creation objects
  90627. hostingScene.dispose();
  90628. // Creates the json header for the env texture
  90629. var info = {
  90630. version: 1,
  90631. width: cubeWidth,
  90632. irradiance: _this._CreateEnvTextureIrradiance(texture),
  90633. specular: {
  90634. mipmaps: [],
  90635. lodGenerationScale: texture.lodGenerationScale
  90636. }
  90637. };
  90638. // Sets the specular image data information
  90639. var position = 0;
  90640. for (var i = 0; i <= mipmapsCount; i++) {
  90641. for (var face = 0; face < 6; face++) {
  90642. var byteLength = specularTextures[i * 6 + face].byteLength;
  90643. info.specular.mipmaps.push({
  90644. length: byteLength,
  90645. position: position
  90646. });
  90647. position += byteLength;
  90648. }
  90649. }
  90650. // Encode the JSON as an array buffer
  90651. var infoString = JSON.stringify(info);
  90652. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  90653. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  90654. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  90655. infoView[i] = infoString.charCodeAt(i);
  90656. }
  90657. // Ends up with a null terminator for easier parsing
  90658. infoView[infoString.length] = 0x00;
  90659. // Computes the final required size and creates the storage
  90660. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  90661. var finalBuffer = new ArrayBuffer(totalSize);
  90662. var finalBufferView = new Uint8Array(finalBuffer);
  90663. var dataView = new DataView(finalBuffer);
  90664. // Copy the magic bytes identifying the file in
  90665. var pos = 0;
  90666. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  90667. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  90668. }
  90669. // Add the json info
  90670. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  90671. pos += infoBuffer.byteLength;
  90672. // Finally inserts the texture data
  90673. for (var i = 0; i <= mipmapsCount; i++) {
  90674. for (var face = 0; face < 6; face++) {
  90675. var dataBuffer = specularTextures[i * 6 + face];
  90676. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  90677. pos += dataBuffer.byteLength;
  90678. }
  90679. }
  90680. // Voila
  90681. return finalBuffer;
  90682. });
  90683. };
  90684. /**
  90685. * Creates a JSON representation of the spherical data.
  90686. * @param texture defines the texture containing the polynomials
  90687. * @return the JSON representation of the spherical info
  90688. */
  90689. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  90690. var polynmials = texture.sphericalPolynomial;
  90691. if (polynmials == null) {
  90692. return null;
  90693. }
  90694. return {
  90695. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  90696. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  90697. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  90698. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  90699. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  90700. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  90701. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  90702. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  90703. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  90704. };
  90705. };
  90706. /**
  90707. * Uploads the texture info contained in the env file to the GPU.
  90708. * @param texture defines the internal texture to upload to
  90709. * @param arrayBuffer defines the buffer cotaining the data to load
  90710. * @param info defines the texture info retrieved through the GetEnvInfo method
  90711. * @returns a promise
  90712. */
  90713. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  90714. if (info.version !== 1) {
  90715. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  90716. }
  90717. var specularInfo = info.specular;
  90718. if (!specularInfo) {
  90719. // Nothing else parsed so far
  90720. return Promise.resolve();
  90721. }
  90722. // Double checks the enclosed info
  90723. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  90724. mipmapsCount = Math.round(mipmapsCount) + 1;
  90725. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  90726. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  90727. }
  90728. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  90729. var imageData = new Array(mipmapsCount);
  90730. for (var i = 0; i < mipmapsCount; i++) {
  90731. imageData[i] = new Array(6);
  90732. for (var face = 0; face < 6; face++) {
  90733. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  90734. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  90735. }
  90736. }
  90737. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  90738. };
  90739. /**
  90740. * Uploads the levels of image data to the GPU.
  90741. * @param texture defines the internal texture to upload to
  90742. * @param imageData defines the array buffer views of image data [mipmap][face]
  90743. * @returns a promise
  90744. */
  90745. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  90746. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  90747. throw new Error("Texture size must be a power of two");
  90748. }
  90749. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  90750. // Gets everything ready.
  90751. var engine = texture.getEngine();
  90752. var expandTexture = false;
  90753. var generateNonLODTextures = false;
  90754. var rgbdPostProcess = null;
  90755. var cubeRtt = null;
  90756. var lodTextures = null;
  90757. var caps = engine.getCaps();
  90758. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  90759. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90760. texture.generateMipMaps = true;
  90761. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  90762. // Add extra process if texture lod is not supported
  90763. if (!caps.textureLOD) {
  90764. expandTexture = false;
  90765. generateNonLODTextures = true;
  90766. lodTextures = {};
  90767. }
  90768. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  90769. else if (engine.webGLVersion < 2) {
  90770. expandTexture = false;
  90771. }
  90772. // If half float available we can uncompress the texture
  90773. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  90774. expandTexture = true;
  90775. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90776. }
  90777. // If full float available we can uncompress the texture
  90778. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  90779. expandTexture = true;
  90780. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90781. }
  90782. // Expand the texture if possible
  90783. if (expandTexture) {
  90784. // Simply run through the decode PP
  90785. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  90786. texture._isRGBD = false;
  90787. texture.invertY = false;
  90788. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  90789. generateDepthBuffer: false,
  90790. generateMipMaps: true,
  90791. generateStencilBuffer: false,
  90792. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  90793. type: texture.type,
  90794. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  90795. });
  90796. }
  90797. else {
  90798. texture._isRGBD = true;
  90799. texture.invertY = true;
  90800. // In case of missing support, applies the same patch than DDS files.
  90801. if (generateNonLODTextures) {
  90802. var mipSlices = 3;
  90803. var scale = texture._lodGenerationScale;
  90804. var offset = texture._lodGenerationOffset;
  90805. for (var i = 0; i < mipSlices; i++) {
  90806. //compute LOD from even spacing in smoothness (matching shader calculation)
  90807. var smoothness = i / (mipSlices - 1);
  90808. var roughness = 1 - smoothness;
  90809. var minLODIndex = offset; // roughness = 0
  90810. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  90811. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  90812. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  90813. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  90814. glTextureFromLod.isCube = true;
  90815. glTextureFromLod.invertY = true;
  90816. glTextureFromLod.generateMipMaps = false;
  90817. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  90818. // Wrap in a base texture for easy binding.
  90819. var lodTexture = new BABYLON.BaseTexture(null);
  90820. lodTexture.isCube = true;
  90821. lodTexture._texture = glTextureFromLod;
  90822. lodTextures[mipmapIndex] = lodTexture;
  90823. switch (i) {
  90824. case 0:
  90825. texture._lodTextureLow = lodTexture;
  90826. break;
  90827. case 1:
  90828. texture._lodTextureMid = lodTexture;
  90829. break;
  90830. case 2:
  90831. texture._lodTextureHigh = lodTexture;
  90832. break;
  90833. }
  90834. }
  90835. }
  90836. }
  90837. var promises = [];
  90838. var _loop_3 = function (i) {
  90839. var _loop_4 = function (face) {
  90840. // Constructs an image element from image data
  90841. var bytes = imageData[i][face];
  90842. var blob = new Blob([bytes], { type: 'image/png' });
  90843. var url = URL.createObjectURL(blob);
  90844. var image = new Image();
  90845. image.src = url;
  90846. // Enqueue promise to upload to the texture.
  90847. var promise = new Promise(function (resolve, reject) {
  90848. image.onload = function () {
  90849. if (expandTexture) {
  90850. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  90851. reject(message);
  90852. }, image);
  90853. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  90854. // Uncompress the data to a RTT
  90855. rgbdPostProcess.onApply = function (effect) {
  90856. effect._bindTexture("textureSampler", tempTexture_1);
  90857. effect.setFloat2("scale", 1, 1);
  90858. };
  90859. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  90860. // Cleanup
  90861. engine.restoreDefaultFramebuffer();
  90862. tempTexture_1.dispose();
  90863. window.URL.revokeObjectURL(url);
  90864. resolve();
  90865. });
  90866. }
  90867. else {
  90868. engine._uploadImageToTexture(texture, image, face, i);
  90869. // Upload the face to the non lod texture support
  90870. if (generateNonLODTextures) {
  90871. var lodTexture = lodTextures[i];
  90872. if (lodTexture) {
  90873. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  90874. }
  90875. }
  90876. resolve();
  90877. }
  90878. };
  90879. image.onerror = function (error) {
  90880. reject(error);
  90881. };
  90882. });
  90883. promises.push(promise);
  90884. };
  90885. // All faces
  90886. for (var face = 0; face < 6; face++) {
  90887. _loop_4(face);
  90888. }
  90889. };
  90890. // All mipmaps up to provided number of images
  90891. for (var i = 0; i < imageData.length; i++) {
  90892. _loop_3(i);
  90893. }
  90894. // Fill remaining mipmaps with black textures.
  90895. if (imageData.length < mipmapsCount) {
  90896. var data = void 0;
  90897. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  90898. var dataLength = size * size * 4;
  90899. switch (texture.type) {
  90900. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  90901. data = new Uint8Array(dataLength);
  90902. break;
  90903. }
  90904. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  90905. data = new Uint16Array(dataLength);
  90906. break;
  90907. }
  90908. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  90909. data = new Float32Array(dataLength);
  90910. break;
  90911. }
  90912. }
  90913. for (var i = imageData.length; i < mipmapsCount; i++) {
  90914. for (var face = 0; face < 6; face++) {
  90915. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  90916. }
  90917. }
  90918. }
  90919. // Once all done, finishes the cleanup and return
  90920. return Promise.all(promises).then(function () {
  90921. // Release temp RTT.
  90922. if (cubeRtt) {
  90923. engine._releaseFramebufferObjects(cubeRtt);
  90924. cubeRtt._swapAndDie(texture);
  90925. }
  90926. // Release temp Post Process.
  90927. if (rgbdPostProcess) {
  90928. rgbdPostProcess.dispose();
  90929. }
  90930. // Flag internal texture as ready in case they are in use.
  90931. if (generateNonLODTextures) {
  90932. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  90933. texture._lodTextureHigh._texture.isReady = true;
  90934. }
  90935. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  90936. texture._lodTextureMid._texture.isReady = true;
  90937. }
  90938. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  90939. texture._lodTextureLow._texture.isReady = true;
  90940. }
  90941. }
  90942. });
  90943. };
  90944. /**
  90945. * Uploads spherical polynomials information to the texture.
  90946. * @param texture defines the texture we are trying to upload the information to
  90947. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  90948. */
  90949. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  90950. if (info.version !== 1) {
  90951. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  90952. }
  90953. var irradianceInfo = info.irradiance;
  90954. if (!irradianceInfo) {
  90955. return;
  90956. }
  90957. var sp = new BABYLON.SphericalPolynomial();
  90958. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  90959. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  90960. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  90961. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  90962. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  90963. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  90964. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  90965. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  90966. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  90967. texture._sphericalPolynomial = sp;
  90968. };
  90969. /**
  90970. * Magic number identifying the env file.
  90971. */
  90972. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  90973. return EnvironmentTextureTools;
  90974. }());
  90975. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  90976. })(BABYLON || (BABYLON = {}));
  90977. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  90978. var BABYLON;
  90979. (function (BABYLON) {
  90980. /**
  90981. * Implementation of the ENV Texture Loader.
  90982. */
  90983. var ENVTextureLoader = /** @class */ (function () {
  90984. function ENVTextureLoader() {
  90985. /**
  90986. * Defines wether the loader supports cascade loading the different faces.
  90987. */
  90988. this.supportCascades = false;
  90989. }
  90990. /**
  90991. * This returns if the loader support the current file information.
  90992. * @param extension defines the file extension of the file being loaded
  90993. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90994. * @param fallback defines the fallback internal texture if any
  90995. * @param isBase64 defines whether the texture is encoded as a base64
  90996. * @param isBuffer defines whether the texture data are stored as a buffer
  90997. * @returns true if the loader can load the specified file
  90998. */
  90999. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  91000. return extension.indexOf(".env") === 0;
  91001. };
  91002. /**
  91003. * Transform the url before loading if required.
  91004. * @param rootUrl the url of the texture
  91005. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91006. * @returns the transformed texture
  91007. */
  91008. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  91009. return rootUrl;
  91010. };
  91011. /**
  91012. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  91013. * @param rootUrl the url of the texture
  91014. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91015. * @returns the fallback texture
  91016. */
  91017. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  91018. return null;
  91019. };
  91020. /**
  91021. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  91022. * @param data contains the texture data
  91023. * @param texture defines the BabylonJS internal texture
  91024. * @param createPolynomials will be true if polynomials have been requested
  91025. * @param onLoad defines the callback to trigger once the texture is ready
  91026. * @param onError defines the callback to trigger in case of error
  91027. */
  91028. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  91029. if (Array.isArray(data)) {
  91030. return;
  91031. }
  91032. data = data;
  91033. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  91034. if (info) {
  91035. texture.width = info.width;
  91036. texture.height = info.width;
  91037. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  91038. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  91039. texture.isReady = true;
  91040. if (onLoad) {
  91041. onLoad();
  91042. }
  91043. });
  91044. }
  91045. else if (onError) {
  91046. onError("Can not parse the environment file", null);
  91047. }
  91048. };
  91049. /**
  91050. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  91051. * @param data contains the texture data
  91052. * @param texture defines the BabylonJS internal texture
  91053. * @param callback defines the method to call once ready to upload
  91054. */
  91055. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  91056. throw ".env not supported in 2d.";
  91057. };
  91058. return ENVTextureLoader;
  91059. }());
  91060. // Register the loader.
  91061. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  91062. })(BABYLON || (BABYLON = {}));
  91063. //# sourceMappingURL=babylon.envTextureLoader.js.map
  91064. var BABYLON;
  91065. (function (BABYLON) {
  91066. /**
  91067. * Renders a layer on top of an existing scene
  91068. */
  91069. var UtilityLayerRenderer = /** @class */ (function () {
  91070. /**
  91071. * Instantiates a UtilityLayerRenderer
  91072. * @param originalScene the original scene that will be rendered on top of
  91073. */
  91074. function UtilityLayerRenderer(
  91075. /** the original scene that will be rendered on top of */
  91076. originalScene) {
  91077. var _this = this;
  91078. this.originalScene = originalScene;
  91079. this._pointerCaptures = {};
  91080. this._lastPointerEvents = {};
  91081. /**
  91082. * If the utility layer should automatically be rendered on top of existing scene
  91083. */
  91084. this.shouldRender = true;
  91085. /**
  91086. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  91087. */
  91088. this.onlyCheckPointerDownEvents = true;
  91089. /**
  91090. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  91091. */
  91092. this.processAllEvents = false;
  91093. /**
  91094. * Observable raised when the pointer move from the utility layer scene to the main scene
  91095. */
  91096. this.onPointerOutObservable = new BABYLON.Observable();
  91097. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  91098. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  91099. this.utilityLayerScene._allowPostProcessClear = false;
  91100. originalScene.getEngine().scenes.pop();
  91101. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  91102. this.utilityLayerScene.detachControl();
  91103. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  91104. if (!_this.processAllEvents) {
  91105. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  91106. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  91107. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  91108. return;
  91109. }
  91110. }
  91111. var pointerEvent = (prePointerInfo.event);
  91112. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  91113. _this._pointerCaptures[pointerEvent.pointerId] = false;
  91114. return;
  91115. }
  91116. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  91117. if (!prePointerInfo.ray && utilityScenePick) {
  91118. prePointerInfo.ray = utilityScenePick.ray;
  91119. }
  91120. // always fire the prepointer oversvable
  91121. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  91122. // allow every non pointer down event to flow to the utility layer
  91123. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  91124. if (!prePointerInfo.skipOnPointerObservable) {
  91125. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  91126. }
  91127. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  91128. _this._pointerCaptures[pointerEvent.pointerId] = false;
  91129. }
  91130. return;
  91131. }
  91132. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  91133. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  91134. if (utilityScenePick && utilityScenePick.hit) {
  91135. if (!prePointerInfo.skipOnPointerObservable) {
  91136. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  91137. }
  91138. prePointerInfo.skipOnPointerObservable = true;
  91139. }
  91140. }
  91141. else {
  91142. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  91143. var pointerEvent_1 = (prePointerInfo.event);
  91144. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  91145. if (originalScenePick && utilityScenePick) {
  91146. // No pick in utility scene
  91147. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  91148. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  91149. // We touched an utility mesh present in the main scene
  91150. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  91151. prePointerInfo.skipOnPointerObservable = true;
  91152. }
  91153. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  91154. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  91155. }
  91156. }
  91157. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  91158. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  91159. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  91160. // If a previous utility layer set this, do not unset this
  91161. if (!prePointerInfo.skipOnPointerObservable) {
  91162. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  91163. }
  91164. }
  91165. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  91166. // We have a pick in both scenes but main is closer than utility
  91167. // We touched an utility mesh present in the main scene
  91168. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  91169. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  91170. prePointerInfo.skipOnPointerObservable = true;
  91171. }
  91172. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  91173. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  91174. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  91175. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  91176. }
  91177. }
  91178. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  91179. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  91180. }
  91181. }
  91182. }
  91183. });
  91184. // Render directly on top of existing scene without clearing
  91185. this.utilityLayerScene.autoClear = false;
  91186. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  91187. if (_this.shouldRender) {
  91188. _this.render();
  91189. }
  91190. });
  91191. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  91192. _this.dispose();
  91193. });
  91194. this._updateCamera();
  91195. }
  91196. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  91197. /**
  91198. * 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)
  91199. */
  91200. get: function () {
  91201. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  91202. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  91203. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  91204. UtilityLayerRenderer._DefaultUtilityLayer = null;
  91205. });
  91206. }
  91207. return UtilityLayerRenderer._DefaultUtilityLayer;
  91208. },
  91209. enumerable: true,
  91210. configurable: true
  91211. });
  91212. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  91213. /**
  91214. * 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)
  91215. */
  91216. get: function () {
  91217. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  91218. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  91219. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  91220. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  91221. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  91222. });
  91223. }
  91224. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  91225. },
  91226. enumerable: true,
  91227. configurable: true
  91228. });
  91229. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  91230. if (!prePointerInfo.skipOnPointerObservable) {
  91231. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  91232. this._lastPointerEvents[pointerEvent.pointerId] = parseInt(pointerEvent.pointerType);
  91233. }
  91234. };
  91235. /**
  91236. * Renders the utility layers scene on top of the original scene
  91237. */
  91238. UtilityLayerRenderer.prototype.render = function () {
  91239. this._updateCamera();
  91240. if (this.utilityLayerScene.activeCamera) {
  91241. // Set the camera's scene to utility layers scene
  91242. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  91243. var camera = this.utilityLayerScene.activeCamera;
  91244. camera._scene = this.utilityLayerScene;
  91245. if (camera.leftCamera) {
  91246. camera.leftCamera._scene = this.utilityLayerScene;
  91247. }
  91248. if (camera.rightCamera) {
  91249. camera.rightCamera._scene = this.utilityLayerScene;
  91250. }
  91251. this.utilityLayerScene.render(false);
  91252. // Reset camera's scene back to original
  91253. camera._scene = oldScene;
  91254. if (camera.leftCamera) {
  91255. camera.leftCamera._scene = oldScene;
  91256. }
  91257. if (camera.rightCamera) {
  91258. camera.rightCamera._scene = oldScene;
  91259. }
  91260. }
  91261. };
  91262. /**
  91263. * Disposes of the renderer
  91264. */
  91265. UtilityLayerRenderer.prototype.dispose = function () {
  91266. this.onPointerOutObservable.clear();
  91267. if (this._afterRenderObserver) {
  91268. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  91269. }
  91270. if (this._sceneDisposeObserver) {
  91271. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  91272. }
  91273. if (this._originalPointerObserver) {
  91274. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  91275. }
  91276. this.utilityLayerScene.dispose();
  91277. };
  91278. UtilityLayerRenderer.prototype._updateCamera = function () {
  91279. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  91280. };
  91281. UtilityLayerRenderer._DefaultUtilityLayer = null;
  91282. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  91283. return UtilityLayerRenderer;
  91284. }());
  91285. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  91286. })(BABYLON || (BABYLON = {}));
  91287. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  91288. //# sourceMappingURL=babylon.behavior.js.map
  91289. var BABYLON;
  91290. (function (BABYLON) {
  91291. /**
  91292. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  91293. */
  91294. var PointerDragBehavior = /** @class */ (function () {
  91295. /**
  91296. * Creates a pointer drag behavior that can be attached to a mesh
  91297. * @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)
  91298. */
  91299. function PointerDragBehavior(options) {
  91300. /**
  91301. * 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)
  91302. */
  91303. this.maxDragAngle = 0;
  91304. /**
  91305. * @hidden
  91306. */
  91307. this._useAlternatePickedPointAboveMaxDragAngle = false;
  91308. /**
  91309. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  91310. */
  91311. this.currentDraggingPointerID = -1;
  91312. /**
  91313. * If the behavior is currently in a dragging state
  91314. */
  91315. this.dragging = false;
  91316. /**
  91317. * 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)
  91318. */
  91319. this.dragDeltaRatio = 0.2;
  91320. /**
  91321. * If the drag plane orientation should be updated during the dragging (Default: true)
  91322. */
  91323. this.updateDragPlane = true;
  91324. // Debug mode will display drag planes to help visualize behavior
  91325. this._debugMode = false;
  91326. this._moving = false;
  91327. /**
  91328. * Fires each time the attached mesh is dragged with the pointer
  91329. * * delta between last drag position and current drag position in world space
  91330. * * dragDistance along the drag axis
  91331. * * dragPlaneNormal normal of the current drag plane used during the drag
  91332. * * dragPlanePoint in world space where the drag intersects the drag plane
  91333. */
  91334. this.onDragObservable = new BABYLON.Observable();
  91335. /**
  91336. * Fires each time a drag begins (eg. mouse down on mesh)
  91337. */
  91338. this.onDragStartObservable = new BABYLON.Observable();
  91339. /**
  91340. * Fires each time a drag ends (eg. mouse release after drag)
  91341. */
  91342. this.onDragEndObservable = new BABYLON.Observable();
  91343. /**
  91344. * If the attached mesh should be moved when dragged
  91345. */
  91346. this.moveAttached = true;
  91347. /**
  91348. * If the drag behavior will react to drag events (Default: true)
  91349. */
  91350. this.enabled = true;
  91351. /**
  91352. * If camera controls should be detached during the drag
  91353. */
  91354. this.detachCameraControls = true;
  91355. /**
  91356. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  91357. */
  91358. this.useObjectOrienationForDragging = true;
  91359. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  91360. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  91361. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  91362. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  91363. this._attachedElement = null;
  91364. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  91365. this._lastPointerRay = {};
  91366. this._dragDelta = new BABYLON.Vector3();
  91367. // Variables to avoid instantiation in the below method
  91368. this._pointA = new BABYLON.Vector3(0, 0, 0);
  91369. this._pointB = new BABYLON.Vector3(0, 0, 0);
  91370. this._pointC = new BABYLON.Vector3(0, 0, 0);
  91371. this._lineA = new BABYLON.Vector3(0, 0, 0);
  91372. this._lineB = new BABYLON.Vector3(0, 0, 0);
  91373. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  91374. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  91375. this._options = options ? options : {};
  91376. var optionCount = 0;
  91377. if (this._options.dragAxis) {
  91378. optionCount++;
  91379. }
  91380. if (this._options.dragPlaneNormal) {
  91381. optionCount++;
  91382. }
  91383. if (optionCount > 1) {
  91384. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  91385. }
  91386. }
  91387. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  91388. /**
  91389. * The name of the behavior
  91390. */
  91391. get: function () {
  91392. return "PointerDrag";
  91393. },
  91394. enumerable: true,
  91395. configurable: true
  91396. });
  91397. /**
  91398. * Initializes the behavior
  91399. */
  91400. PointerDragBehavior.prototype.init = function () { };
  91401. /**
  91402. * Attaches the drag behavior the passed in mesh
  91403. * @param ownerNode The mesh that will be dragged around once attached
  91404. */
  91405. PointerDragBehavior.prototype.attach = function (ownerNode) {
  91406. var _this = this;
  91407. this._scene = ownerNode.getScene();
  91408. this._attachedNode = ownerNode;
  91409. // Initialize drag plane to not interfere with existing scene
  91410. if (!PointerDragBehavior._planeScene) {
  91411. if (this._debugMode) {
  91412. PointerDragBehavior._planeScene = this._scene;
  91413. }
  91414. else {
  91415. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  91416. PointerDragBehavior._planeScene.detachControl();
  91417. this._scene.getEngine().scenes.pop();
  91418. this._scene.onDisposeObservable.addOnce(function () {
  91419. PointerDragBehavior._planeScene.dispose();
  91420. PointerDragBehavior._planeScene = null;
  91421. });
  91422. }
  91423. }
  91424. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  91425. // State of the drag
  91426. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  91427. var pickPredicate = function (m) {
  91428. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  91429. };
  91430. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  91431. if (!_this.enabled) {
  91432. return;
  91433. }
  91434. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  91435. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  91436. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  91437. }
  91438. }
  91439. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  91440. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  91441. _this.releaseDrag();
  91442. }
  91443. }
  91444. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  91445. var pointerId = pointerInfo.event.pointerId;
  91446. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  91447. if (!_this._lastPointerRay[pointerId]) {
  91448. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  91449. }
  91450. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  91451. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  91452. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  91453. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  91454. _this._moveDrag(pointerInfo.pickInfo.ray);
  91455. }
  91456. }
  91457. }
  91458. });
  91459. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  91460. if (_this._moving && _this.moveAttached) {
  91461. // Slowly move mesh to avoid jitter
  91462. _this._targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  91463. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  91464. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  91465. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  91466. }
  91467. });
  91468. };
  91469. PointerDragBehavior.prototype.releaseDrag = function () {
  91470. this.dragging = false;
  91471. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  91472. this.currentDraggingPointerID = -1;
  91473. this._moving = false;
  91474. // Reattach camera controls
  91475. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  91476. this._scene.activeCamera.attachControl(this._attachedElement, true);
  91477. }
  91478. };
  91479. /**
  91480. * Simulates the start of a pointer drag event on the behavior
  91481. * @param pointerId pointerID of the pointer that should be simulated (Default: 1 for mouse pointer)
  91482. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  91483. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  91484. */
  91485. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  91486. if (pointerId === void 0) { pointerId = 1; }
  91487. this._startDrag(pointerId, fromRay, startPickedPoint);
  91488. if (this._lastPointerRay[pointerId]) {
  91489. // if there was a last pointer ray drag the object there
  91490. this._moveDrag(this._lastPointerRay[pointerId]);
  91491. }
  91492. };
  91493. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  91494. if (pointerId === void 0) { pointerId = 1; }
  91495. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  91496. return;
  91497. }
  91498. // Create start ray from the camera to the object
  91499. if (fromRay) {
  91500. this._startDragRay.direction.copyFrom(fromRay.direction);
  91501. this._startDragRay.origin.copyFrom(fromRay.origin);
  91502. }
  91503. else {
  91504. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  91505. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  91506. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  91507. }
  91508. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  91509. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  91510. if (pickedPoint) {
  91511. this.dragging = true;
  91512. this.currentDraggingPointerID = 1;
  91513. this.lastDragPosition.copyFrom(pickedPoint);
  91514. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  91515. this._targetPosition.copyFrom(this._attachedNode.absolutePosition);
  91516. // Detatch camera controls
  91517. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  91518. if (this._scene.activeCamera.inputs.attachedElement) {
  91519. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  91520. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  91521. }
  91522. else {
  91523. this._attachedElement = null;
  91524. }
  91525. }
  91526. }
  91527. };
  91528. PointerDragBehavior.prototype._moveDrag = function (ray) {
  91529. this._moving = true;
  91530. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  91531. if (pickedPoint) {
  91532. if (this.updateDragPlane) {
  91533. this._updateDragPlanePosition(ray, pickedPoint);
  91534. }
  91535. var dragLength = 0;
  91536. // depending on the drag mode option drag accordingly
  91537. if (this._options.dragAxis) {
  91538. // Convert local drag axis to world
  91539. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  91540. // Project delta drag from the drag plane onto the drag axis
  91541. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  91542. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  91543. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  91544. }
  91545. else {
  91546. dragLength = this._dragDelta.length();
  91547. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  91548. }
  91549. this._targetPosition.addInPlace(this._dragDelta);
  91550. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  91551. this.lastDragPosition.copyFrom(pickedPoint);
  91552. }
  91553. };
  91554. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  91555. var _this = this;
  91556. if (!ray) {
  91557. return null;
  91558. }
  91559. // Calculate angle between plane normal and ray
  91560. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  91561. // Correct if ray is casted from oposite side
  91562. if (angle > Math.PI / 2) {
  91563. angle = Math.PI - angle;
  91564. }
  91565. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  91566. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  91567. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  91568. // Invert ray direction along the towards object axis
  91569. this._tmpVector.copyFrom(ray.direction);
  91570. this._attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  91571. this._alternatePickedPoint.normalize();
  91572. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  91573. this._tmpVector.addInPlace(this._alternatePickedPoint);
  91574. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  91575. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  91576. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  91577. this._alternatePickedPoint.addInPlace(this._tmpVector);
  91578. this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition);
  91579. return this._alternatePickedPoint;
  91580. }
  91581. else {
  91582. return null;
  91583. }
  91584. }
  91585. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  91586. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  91587. return pickResult.pickedPoint;
  91588. }
  91589. else {
  91590. return null;
  91591. }
  91592. };
  91593. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  91594. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  91595. this._pointA.copyFrom(dragPlanePosition);
  91596. if (this._options.dragAxis) {
  91597. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  91598. // Calculate plane normal in direction of camera but perpendicular to drag axis
  91599. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  91600. ray.origin.subtractToRef(this._pointA, this._pointC);
  91601. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  91602. // Get perpendicular line from direction to camera and drag axis
  91603. this._pointB.subtractToRef(this._pointA, this._lineA);
  91604. this._pointC.subtractToRef(this._pointA, this._lineB);
  91605. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  91606. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  91607. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  91608. this._lookAt.normalize();
  91609. this._dragPlane.position.copyFrom(this._pointA);
  91610. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  91611. this._dragPlane.lookAt(this._lookAt);
  91612. }
  91613. else if (this._options.dragPlaneNormal) {
  91614. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  91615. this._dragPlane.position.copyFrom(this._pointA);
  91616. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  91617. this._dragPlane.lookAt(this._lookAt);
  91618. }
  91619. else {
  91620. this._dragPlane.position.copyFrom(this._pointA);
  91621. this._dragPlane.lookAt(ray.origin);
  91622. }
  91623. this._dragPlane.computeWorldMatrix(true);
  91624. };
  91625. /**
  91626. * Detaches the behavior from the mesh
  91627. */
  91628. PointerDragBehavior.prototype.detach = function () {
  91629. if (this._pointerObserver) {
  91630. this._scene.onPointerObservable.remove(this._pointerObserver);
  91631. }
  91632. if (this._beforeRenderObserver) {
  91633. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  91634. }
  91635. };
  91636. return PointerDragBehavior;
  91637. }());
  91638. BABYLON.PointerDragBehavior = PointerDragBehavior;
  91639. })(BABYLON || (BABYLON = {}));
  91640. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  91641. var BABYLON;
  91642. (function (BABYLON) {
  91643. /**
  91644. * A behavior that when attached to a mesh will allow the mesh to be scaled
  91645. */
  91646. var MultiPointerScaleBehavior = /** @class */ (function () {
  91647. function MultiPointerScaleBehavior() {
  91648. this._startDistance = 0;
  91649. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  91650. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  91651. this._sceneRenderObserver = null;
  91652. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  91653. this._dragBehaviorA.moveAttached = false;
  91654. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  91655. this._dragBehaviorB.moveAttached = false;
  91656. }
  91657. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  91658. /**
  91659. * The name of the behavior
  91660. */
  91661. get: function () {
  91662. return "MultiPointerScale";
  91663. },
  91664. enumerable: true,
  91665. configurable: true
  91666. });
  91667. /**
  91668. * Initializes the behavior
  91669. */
  91670. MultiPointerScaleBehavior.prototype.init = function () { };
  91671. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  91672. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  91673. };
  91674. /**
  91675. * Attaches the scale behavior the passed in mesh
  91676. * @param ownerNode The mesh that will be scaled around once attached
  91677. */
  91678. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  91679. var _this = this;
  91680. this._ownerNode = ownerNode;
  91681. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  91682. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  91683. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  91684. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  91685. _this._dragBehaviorA.releaseDrag();
  91686. }
  91687. else {
  91688. _this._initialScale.copyFrom(ownerNode.scaling);
  91689. _this._startDistance = _this._getCurrentDistance();
  91690. }
  91691. }
  91692. });
  91693. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  91694. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  91695. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  91696. _this._dragBehaviorB.releaseDrag();
  91697. }
  91698. else {
  91699. _this._initialScale.copyFrom(ownerNode.scaling);
  91700. _this._startDistance = _this._getCurrentDistance();
  91701. }
  91702. }
  91703. });
  91704. // Once both drag behaviors are active scale based on the distance between the two pointers
  91705. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  91706. behavior.onDragObservable.add(function () {
  91707. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  91708. var ratio = _this._getCurrentDistance() / _this._startDistance;
  91709. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  91710. }
  91711. });
  91712. });
  91713. ownerNode.addBehavior(this._dragBehaviorA);
  91714. ownerNode.addBehavior(this._dragBehaviorB);
  91715. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  91716. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  91717. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  91718. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  91719. if (change.length() > 0.01) {
  91720. ownerNode.scaling.addInPlace(change);
  91721. }
  91722. }
  91723. });
  91724. };
  91725. /**
  91726. * Detaches the behavior from the mesh
  91727. */
  91728. MultiPointerScaleBehavior.prototype.detach = function () {
  91729. var _this = this;
  91730. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  91731. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  91732. behavior.onDragStartObservable.clear();
  91733. behavior.onDragObservable.clear();
  91734. _this._ownerNode.removeBehavior(behavior);
  91735. });
  91736. };
  91737. return MultiPointerScaleBehavior;
  91738. }());
  91739. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  91740. })(BABYLON || (BABYLON = {}));
  91741. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  91742. var BABYLON;
  91743. (function (BABYLON) {
  91744. /**
  91745. * 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
  91746. */
  91747. var SixDofDragBehavior = /** @class */ (function () {
  91748. function SixDofDragBehavior() {
  91749. this._sceneRenderObserver = null;
  91750. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  91751. this._moving = false;
  91752. this._startingOrientation = new BABYLON.Quaternion();
  91753. /**
  91754. * 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)
  91755. */
  91756. this.zDragFactor = 3;
  91757. /**
  91758. * If the behavior is currently in a dragging state
  91759. */
  91760. this.dragging = false;
  91761. /**
  91762. * 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)
  91763. */
  91764. this.dragDeltaRatio = 0.2;
  91765. /**
  91766. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  91767. */
  91768. this.currentDraggingPointerID = -1;
  91769. /**
  91770. * If camera controls should be detached during the drag
  91771. */
  91772. this.detachCameraControls = true;
  91773. }
  91774. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  91775. /**
  91776. * The name of the behavior
  91777. */
  91778. get: function () {
  91779. return "SixDofDrag";
  91780. },
  91781. enumerable: true,
  91782. configurable: true
  91783. });
  91784. /**
  91785. * Initializes the behavior
  91786. */
  91787. SixDofDragBehavior.prototype.init = function () { };
  91788. /**
  91789. * Attaches the scale behavior the passed in mesh
  91790. * @param ownerNode The mesh that will be scaled around once attached
  91791. */
  91792. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  91793. var _this = this;
  91794. this._ownerNode = ownerNode;
  91795. this._scene = this._ownerNode.getScene();
  91796. if (!SixDofDragBehavior._virtualScene) {
  91797. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  91798. this._scene.getEngine().scenes.pop();
  91799. }
  91800. var pickedMesh = null;
  91801. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  91802. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  91803. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  91804. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  91805. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  91806. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  91807. var pickPredicate = function (m) {
  91808. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  91809. };
  91810. var attachedElement = null;
  91811. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  91812. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  91813. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  91814. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  91815. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  91816. }
  91817. pickedMesh = _this._ownerNode;
  91818. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  91819. // Set position and orientation of the controller
  91820. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  91821. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  91822. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  91823. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  91824. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  91825. if (!pickedMesh.rotationQuaternion) {
  91826. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  91827. }
  91828. var oldParent = pickedMesh.parent;
  91829. pickedMesh.setParent(null);
  91830. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  91831. pickedMesh.setParent(oldParent);
  91832. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  91833. // Update state
  91834. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  91835. _this.dragging = true;
  91836. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  91837. // Detatch camera controls
  91838. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  91839. if (_this._scene.activeCamera.inputs.attachedElement) {
  91840. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  91841. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  91842. }
  91843. else {
  91844. attachedElement = null;
  91845. }
  91846. }
  91847. }
  91848. }
  91849. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  91850. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  91851. _this.dragging = false;
  91852. _this._moving = false;
  91853. _this.currentDraggingPointerID = -1;
  91854. pickedMesh = null;
  91855. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  91856. // Reattach camera controls
  91857. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  91858. _this._scene.activeCamera.attachControl(attachedElement, true);
  91859. }
  91860. }
  91861. }
  91862. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  91863. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  91864. var zDragFactor = _this.zDragFactor;
  91865. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  91866. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  91867. zDragFactor = 0;
  91868. }
  91869. // Calculate controller drag distance in controller space
  91870. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  91871. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  91872. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  91873. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  91874. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  91875. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  91876. if (_this._virtualDragMesh.position.z < 0) {
  91877. _this._virtualDragMesh.position.z = 0;
  91878. }
  91879. // Update the controller position
  91880. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  91881. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  91882. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  91883. // Move the virtualObjectsPosition into the picked mesh's space if needed
  91884. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  91885. if (pickedMesh.parent) {
  91886. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  91887. }
  91888. if (!_this._moving) {
  91889. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  91890. }
  91891. _this._moving = true;
  91892. }
  91893. }
  91894. });
  91895. var tmpQuaternion = new BABYLON.Quaternion();
  91896. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  91897. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  91898. if (_this.dragging && _this._moving && pickedMesh) {
  91899. // Slowly move mesh to avoid jitter
  91900. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  91901. // Get change in rotation
  91902. tmpQuaternion.copyFrom(_this._startingOrientation);
  91903. tmpQuaternion.x = -tmpQuaternion.x;
  91904. tmpQuaternion.y = -tmpQuaternion.y;
  91905. tmpQuaternion.z = -tmpQuaternion.z;
  91906. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  91907. // Convert change in rotation to only y axis rotation
  91908. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  91909. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  91910. // Slowly move mesh to avoid jitter
  91911. var oldParent = pickedMesh.parent;
  91912. pickedMesh.setParent(null);
  91913. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  91914. pickedMesh.setParent(oldParent);
  91915. }
  91916. });
  91917. };
  91918. /**
  91919. * Detaches the behavior from the mesh
  91920. */
  91921. SixDofDragBehavior.prototype.detach = function () {
  91922. if (this._scene) {
  91923. this._scene.onPointerObservable.remove(this._pointerObserver);
  91924. }
  91925. if (this._ownerNode) {
  91926. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  91927. }
  91928. if (this._virtualOriginMesh) {
  91929. this._virtualOriginMesh.dispose();
  91930. }
  91931. if (this._virtualDragMesh) {
  91932. this._virtualDragMesh.dispose();
  91933. }
  91934. };
  91935. return SixDofDragBehavior;
  91936. }());
  91937. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  91938. })(BABYLON || (BABYLON = {}));
  91939. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  91940. var BABYLON;
  91941. (function (BABYLON) {
  91942. /**
  91943. * @hidden
  91944. */
  91945. var FaceDirectionInfo = /** @class */ (function () {
  91946. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  91947. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  91948. if (diff === void 0) { diff = 0; }
  91949. if (ignore === void 0) { ignore = false; }
  91950. this.direction = direction;
  91951. this.rotatedDirection = rotatedDirection;
  91952. this.diff = diff;
  91953. this.ignore = ignore;
  91954. }
  91955. return FaceDirectionInfo;
  91956. }());
  91957. /**
  91958. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  91959. */
  91960. var AttachToBoxBehavior = /** @class */ (function () {
  91961. /**
  91962. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  91963. * @param ui The transform node that should be attched to the mesh
  91964. */
  91965. function AttachToBoxBehavior(ui) {
  91966. this.ui = ui;
  91967. /**
  91968. * The name of the behavior
  91969. */
  91970. this.name = "AttachToBoxBehavior";
  91971. /**
  91972. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  91973. */
  91974. this.distanceAwayFromFace = 0.15;
  91975. /**
  91976. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  91977. */
  91978. this.distanceAwayFromBottomOfFace = 0.15;
  91979. 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))];
  91980. this._tmpMatrix = new BABYLON.Matrix();
  91981. this._tmpVector = new BABYLON.Vector3();
  91982. this._zeroVector = BABYLON.Vector3.Zero();
  91983. this._lookAtTmpMatrix = new BABYLON.Matrix();
  91984. /* Does nothing */
  91985. }
  91986. /**
  91987. * Initializes the behavior
  91988. */
  91989. AttachToBoxBehavior.prototype.init = function () {
  91990. /* Does nothing */
  91991. };
  91992. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  91993. var _this = this;
  91994. // Go over each face and calculate the angle between the face's normal and targetDirection
  91995. this._faceVectors.forEach(function (v) {
  91996. if (!_this._target.rotationQuaternion) {
  91997. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  91998. }
  91999. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  92000. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  92001. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  92002. });
  92003. // Return the face information of the one with the normal closeset to target direction
  92004. return this._faceVectors.reduce(function (min, p) {
  92005. if (min.ignore) {
  92006. return p;
  92007. }
  92008. else if (p.ignore) {
  92009. return min;
  92010. }
  92011. else {
  92012. return min.diff < p.diff ? min : p;
  92013. }
  92014. }, this._faceVectors[0]);
  92015. };
  92016. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  92017. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  92018. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  92019. this._lookAtTmpMatrix.invert();
  92020. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  92021. };
  92022. /**
  92023. * Attaches the AttachToBoxBehavior to the passed in mesh
  92024. * @param target The mesh that the specified node will be attached to
  92025. */
  92026. AttachToBoxBehavior.prototype.attach = function (target) {
  92027. var _this = this;
  92028. this._target = target;
  92029. this._scene = this._target.getScene();
  92030. // Every frame, update the app bars position
  92031. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  92032. if (!_this._scene.activeCamera) {
  92033. return;
  92034. }
  92035. // Find the face closest to the cameras position
  92036. var cameraPos = _this._scene.activeCamera.position;
  92037. if (_this._scene.activeCamera.devicePosition) {
  92038. cameraPos = _this._scene.activeCamera.devicePosition;
  92039. }
  92040. var facing = _this._closestFace(cameraPos.subtract(target.position));
  92041. if (_this._scene.activeCamera.leftCamera) {
  92042. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  92043. }
  92044. else {
  92045. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  92046. }
  92047. // Get camera up direction
  92048. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  92049. // Ignore faces to not select a parrelel face for the up vector of the UI
  92050. _this._faceVectors.forEach(function (v) {
  92051. if (facing.direction.x && v.direction.x) {
  92052. v.ignore = true;
  92053. }
  92054. if (facing.direction.y && v.direction.y) {
  92055. v.ignore = true;
  92056. }
  92057. if (facing.direction.z && v.direction.z) {
  92058. v.ignore = true;
  92059. }
  92060. });
  92061. var facingUp = _this._closestFace(_this._tmpVector);
  92062. // Unignore faces
  92063. _this._faceVectors.forEach(function (v) {
  92064. v.ignore = false;
  92065. });
  92066. // Position the app bar on that face
  92067. _this.ui.position.copyFrom(target.position);
  92068. if (facing.direction.x) {
  92069. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  92070. _this.ui.position.addInPlace(_this._tmpVector);
  92071. }
  92072. if (facing.direction.y) {
  92073. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  92074. _this.ui.position.addInPlace(_this._tmpVector);
  92075. }
  92076. if (facing.direction.z) {
  92077. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  92078. _this.ui.position.addInPlace(_this._tmpVector);
  92079. }
  92080. // Rotate to be oriented properly to the camera
  92081. if (!_this.ui.rotationQuaternion) {
  92082. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  92083. }
  92084. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  92085. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  92086. // Place ui the correct distance from the bottom of the mesh
  92087. if (facingUp.direction.x) {
  92088. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  92089. }
  92090. if (facingUp.direction.y) {
  92091. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  92092. }
  92093. if (facingUp.direction.z) {
  92094. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  92095. }
  92096. _this.ui.position.addInPlace(_this._tmpVector);
  92097. });
  92098. };
  92099. /**
  92100. * Detaches the behavior from the mesh
  92101. */
  92102. AttachToBoxBehavior.prototype.detach = function () {
  92103. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  92104. };
  92105. return AttachToBoxBehavior;
  92106. }());
  92107. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  92108. })(BABYLON || (BABYLON = {}));
  92109. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  92110. var BABYLON;
  92111. (function (BABYLON) {
  92112. /**
  92113. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  92114. */
  92115. var FadeInOutBehavior = /** @class */ (function () {
  92116. /**
  92117. * Instatiates the FadeInOutBehavior
  92118. */
  92119. function FadeInOutBehavior() {
  92120. var _this = this;
  92121. /**
  92122. * Time in milliseconds to delay before fading in (Default: 0)
  92123. */
  92124. this.delay = 0;
  92125. /**
  92126. * Time in milliseconds for the mesh to fade in (Default: 300)
  92127. */
  92128. this.fadeInTime = 300;
  92129. this._millisecondsPerFrame = 1000 / 60;
  92130. this._hovered = false;
  92131. this._hoverValue = 0;
  92132. this._ownerNode = null;
  92133. this._update = function () {
  92134. if (_this._ownerNode) {
  92135. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  92136. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  92137. if (_this._ownerNode.visibility > 1) {
  92138. _this._setAllVisibility(_this._ownerNode, 1);
  92139. _this._hoverValue = _this.fadeInTime + _this.delay;
  92140. return;
  92141. }
  92142. else if (_this._ownerNode.visibility < 0) {
  92143. _this._setAllVisibility(_this._ownerNode, 0);
  92144. if (_this._hoverValue < 0) {
  92145. _this._hoverValue = 0;
  92146. return;
  92147. }
  92148. }
  92149. setTimeout(_this._update, _this._millisecondsPerFrame);
  92150. }
  92151. };
  92152. }
  92153. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  92154. /**
  92155. * The name of the behavior
  92156. */
  92157. get: function () {
  92158. return "FadeInOut";
  92159. },
  92160. enumerable: true,
  92161. configurable: true
  92162. });
  92163. /**
  92164. * Initializes the behavior
  92165. */
  92166. FadeInOutBehavior.prototype.init = function () {
  92167. };
  92168. /**
  92169. * Attaches the fade behavior on the passed in mesh
  92170. * @param ownerNode The mesh that will be faded in/out once attached
  92171. */
  92172. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  92173. this._ownerNode = ownerNode;
  92174. this._setAllVisibility(this._ownerNode, 0);
  92175. };
  92176. /**
  92177. * Detaches the behavior from the mesh
  92178. */
  92179. FadeInOutBehavior.prototype.detach = function () {
  92180. this._ownerNode = null;
  92181. };
  92182. /**
  92183. * Triggers the mesh to begin fading in or out
  92184. * @param value if the object should fade in or out (true to fade in)
  92185. */
  92186. FadeInOutBehavior.prototype.fadeIn = function (value) {
  92187. this._hovered = value;
  92188. this._update();
  92189. };
  92190. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  92191. var _this = this;
  92192. mesh.visibility = value;
  92193. mesh.getChildMeshes().forEach(function (c) {
  92194. _this._setAllVisibility(c, value);
  92195. });
  92196. };
  92197. return FadeInOutBehavior;
  92198. }());
  92199. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  92200. })(BABYLON || (BABYLON = {}));
  92201. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  92202. var BABYLON;
  92203. (function (BABYLON) {
  92204. /**
  92205. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  92206. */
  92207. var Gizmo = /** @class */ (function () {
  92208. /**
  92209. * Creates a gizmo
  92210. * @param gizmoLayer The utility layer the gizmo will be added to
  92211. */
  92212. function Gizmo(
  92213. /** The utility layer the gizmo will be added to */
  92214. gizmoLayer) {
  92215. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92216. var _this = this;
  92217. this.gizmoLayer = gizmoLayer;
  92218. /**
  92219. * Ratio for the scale of the gizmo (Default: 1)
  92220. */
  92221. this.scaleRatio = 1;
  92222. this._tmpMatrix = new BABYLON.Matrix();
  92223. /**
  92224. * If a custom mesh has been set (Default: false)
  92225. */
  92226. this._customMeshSet = false;
  92227. /**
  92228. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  92229. */
  92230. this.updateGizmoRotationToMatchAttachedMesh = true;
  92231. /**
  92232. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  92233. */
  92234. this.updateGizmoPositionToMatchAttachedMesh = true;
  92235. /**
  92236. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  92237. */
  92238. this._updateScale = true;
  92239. this._interactionsEnabled = true;
  92240. this._tempVector = new BABYLON.Vector3();
  92241. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  92242. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  92243. _this._update();
  92244. });
  92245. this.attachedMesh = null;
  92246. }
  92247. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  92248. /**
  92249. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  92250. * * When set, interactions will be enabled
  92251. */
  92252. get: function () {
  92253. return this._attachedMesh;
  92254. },
  92255. set: function (value) {
  92256. this._attachedMesh = value;
  92257. this._rootMesh.setEnabled(value ? true : false);
  92258. this._attachedMeshChanged(value);
  92259. },
  92260. enumerable: true,
  92261. configurable: true
  92262. });
  92263. /**
  92264. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  92265. * @param mesh The mesh to replace the default mesh of the gizmo
  92266. */
  92267. Gizmo.prototype.setCustomMesh = function (mesh) {
  92268. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  92269. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  92270. }
  92271. this._rootMesh.getChildMeshes().forEach(function (c) {
  92272. c.dispose();
  92273. });
  92274. mesh.parent = this._rootMesh;
  92275. this._customMeshSet = true;
  92276. };
  92277. Gizmo.prototype._attachedMeshChanged = function (value) {
  92278. };
  92279. /**
  92280. * @hidden
  92281. * Updates the gizmo to match the attached mesh's position/rotation
  92282. */
  92283. Gizmo.prototype._update = function () {
  92284. if (this.attachedMesh) {
  92285. if (this.updateGizmoRotationToMatchAttachedMesh) {
  92286. if (!this._rootMesh.rotationQuaternion) {
  92287. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  92288. }
  92289. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  92290. this._tempVector.copyFrom(this.attachedMesh.scaling);
  92291. if (this.attachedMesh.scaling.x < 0) {
  92292. this.attachedMesh.scaling.x *= -1;
  92293. }
  92294. if (this.attachedMesh.scaling.y < 0) {
  92295. this.attachedMesh.scaling.y *= -1;
  92296. }
  92297. if (this.attachedMesh.scaling.z < 0) {
  92298. this.attachedMesh.scaling.z *= -1;
  92299. }
  92300. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  92301. this.attachedMesh.scaling.copyFrom(this._tempVector);
  92302. this.attachedMesh.computeWorldMatrix();
  92303. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  92304. }
  92305. else if (this._rootMesh.rotationQuaternion) {
  92306. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  92307. }
  92308. if (this.updateGizmoPositionToMatchAttachedMesh) {
  92309. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  92310. }
  92311. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  92312. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  92313. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  92314. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  92315. }
  92316. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  92317. var dist = this._tempVector.length() * this.scaleRatio;
  92318. this._rootMesh.scaling.set(dist, dist, dist);
  92319. }
  92320. }
  92321. };
  92322. /**
  92323. * Disposes of the gizmo
  92324. */
  92325. Gizmo.prototype.dispose = function () {
  92326. this._rootMesh.dispose();
  92327. if (this._beforeRenderObserver) {
  92328. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  92329. }
  92330. };
  92331. return Gizmo;
  92332. }());
  92333. BABYLON.Gizmo = Gizmo;
  92334. })(BABYLON || (BABYLON = {}));
  92335. //# sourceMappingURL=babylon.gizmo.js.map
  92336. var BABYLON;
  92337. (function (BABYLON) {
  92338. /**
  92339. * Single axis drag gizmo
  92340. */
  92341. var AxisDragGizmo = /** @class */ (function (_super) {
  92342. __extends(AxisDragGizmo, _super);
  92343. /**
  92344. * Creates an AxisDragGizmo
  92345. * @param gizmoLayer The utility layer the gizmo will be added to
  92346. * @param dragAxis The axis which the gizmo will be able to drag on
  92347. * @param color The color of the gizmo
  92348. */
  92349. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  92350. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  92351. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92352. var _this = _super.call(this, gizmoLayer) || this;
  92353. _this._pointerObserver = null;
  92354. /**
  92355. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92356. */
  92357. _this.snapDistance = 0;
  92358. /**
  92359. * Event that fires each time the gizmo snaps to a new location.
  92360. * * snapDistance is the the change in distance
  92361. */
  92362. _this.onSnapObservable = new BABYLON.Observable();
  92363. // Create Material
  92364. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92365. coloredMaterial.disableLighting = true;
  92366. coloredMaterial.emissiveColor = color;
  92367. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92368. hoverMaterial.disableLighting = true;
  92369. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  92370. // Build mesh on root node
  92371. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92372. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  92373. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  92374. arrowTail.color = coloredMaterial.emissiveColor;
  92375. arrow.addChild(arrowMesh);
  92376. arrow.addChild(arrowTail);
  92377. // Position arrow pointing in its drag axis
  92378. arrowMesh.scaling.scaleInPlace(0.05);
  92379. arrowMesh.material = coloredMaterial;
  92380. arrowMesh.rotation.x = Math.PI / 2;
  92381. arrowMesh.position.z += 0.3;
  92382. arrowTail.scaling.scaleInPlace(0.26);
  92383. arrowTail.rotation.x = Math.PI / 2;
  92384. arrowTail.material = coloredMaterial;
  92385. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  92386. arrow.scaling.scaleInPlace(1 / 3);
  92387. _this._rootMesh.addChild(arrow);
  92388. var currentSnapDragDistance = 0;
  92389. var tmpVector = new BABYLON.Vector3();
  92390. var tmpSnapEvent = { snapDistance: 0 };
  92391. // Add drag behavior to handle events when the gizmo is dragged
  92392. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  92393. _this.dragBehavior.moveAttached = false;
  92394. _this._rootMesh.addBehavior(_this.dragBehavior);
  92395. var localDelta = new BABYLON.Vector3();
  92396. var tmpMatrix = new BABYLON.Matrix();
  92397. _this.dragBehavior.onDragObservable.add(function (event) {
  92398. if (_this.attachedMesh) {
  92399. // Convert delta to local translation if it has a parent
  92400. if (_this.attachedMesh.parent) {
  92401. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  92402. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  92403. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  92404. }
  92405. else {
  92406. localDelta.copyFrom(event.delta);
  92407. }
  92408. // Snapping logic
  92409. if (_this.snapDistance == 0) {
  92410. _this.attachedMesh.position.addInPlace(localDelta);
  92411. }
  92412. else {
  92413. currentSnapDragDistance += event.dragDistance;
  92414. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  92415. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  92416. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  92417. localDelta.normalizeToRef(tmpVector);
  92418. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  92419. _this.attachedMesh.position.addInPlace(tmpVector);
  92420. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  92421. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  92422. }
  92423. }
  92424. }
  92425. });
  92426. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  92427. if (_this._customMeshSet) {
  92428. return;
  92429. }
  92430. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  92431. var material = isHovered ? hoverMaterial : coloredMaterial;
  92432. _this._rootMesh.getChildMeshes().forEach(function (m) {
  92433. m.material = material;
  92434. if (m.color) {
  92435. m.color = material.emissiveColor;
  92436. }
  92437. });
  92438. });
  92439. return _this;
  92440. }
  92441. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  92442. if (this.dragBehavior) {
  92443. this.dragBehavior.enabled = value ? true : false;
  92444. }
  92445. };
  92446. /**
  92447. * Disposes of the gizmo
  92448. */
  92449. AxisDragGizmo.prototype.dispose = function () {
  92450. this.onSnapObservable.clear();
  92451. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  92452. this.dragBehavior.detach();
  92453. _super.prototype.dispose.call(this);
  92454. };
  92455. return AxisDragGizmo;
  92456. }(BABYLON.Gizmo));
  92457. BABYLON.AxisDragGizmo = AxisDragGizmo;
  92458. })(BABYLON || (BABYLON = {}));
  92459. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  92460. var BABYLON;
  92461. (function (BABYLON) {
  92462. /**
  92463. * Single axis scale gizmo
  92464. */
  92465. var AxisScaleGizmo = /** @class */ (function (_super) {
  92466. __extends(AxisScaleGizmo, _super);
  92467. /**
  92468. * Creates an AxisScaleGizmo
  92469. * @param gizmoLayer The utility layer the gizmo will be added to
  92470. * @param dragAxis The axis which the gizmo will be able to scale on
  92471. * @param color The color of the gizmo
  92472. */
  92473. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  92474. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  92475. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92476. var _this = _super.call(this, gizmoLayer) || this;
  92477. _this._pointerObserver = null;
  92478. /**
  92479. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92480. */
  92481. _this.snapDistance = 0;
  92482. /**
  92483. * Event that fires each time the gizmo snaps to a new location.
  92484. * * snapDistance is the the change in distance
  92485. */
  92486. _this.onSnapObservable = new BABYLON.Observable();
  92487. /**
  92488. * If the scaling operation should be done on all axis (default: false)
  92489. */
  92490. _this.uniformScaling = false;
  92491. // Create Material
  92492. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92493. _this._coloredMaterial.disableLighting = true;
  92494. _this._coloredMaterial.emissiveColor = color;
  92495. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92496. hoverMaterial.disableLighting = true;
  92497. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  92498. // Build mesh on root node
  92499. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92500. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  92501. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  92502. arrowTail.color = _this._coloredMaterial.emissiveColor;
  92503. arrow.addChild(arrowMesh);
  92504. arrow.addChild(arrowTail);
  92505. // Position arrow pointing in its drag axis
  92506. arrowMesh.scaling.scaleInPlace(0.1);
  92507. arrowMesh.material = _this._coloredMaterial;
  92508. arrowMesh.rotation.x = Math.PI / 2;
  92509. arrowMesh.position.z += 0.3;
  92510. arrowTail.scaling.scaleInPlace(0.26);
  92511. arrowTail.rotation.x = Math.PI / 2;
  92512. arrowTail.material = _this._coloredMaterial;
  92513. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  92514. _this._rootMesh.addChild(arrow);
  92515. arrow.scaling.scaleInPlace(1 / 3);
  92516. // Add drag behavior to handle events when the gizmo is dragged
  92517. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  92518. _this.dragBehavior.moveAttached = false;
  92519. _this._rootMesh.addBehavior(_this.dragBehavior);
  92520. var currentSnapDragDistance = 0;
  92521. var tmpVector = new BABYLON.Vector3();
  92522. var tmpSnapEvent = { snapDistance: 0 };
  92523. _this.dragBehavior.onDragObservable.add(function (event) {
  92524. if (_this.attachedMesh) {
  92525. // Snapping logic
  92526. var snapped = false;
  92527. var dragSteps = 0;
  92528. if (_this.uniformScaling) {
  92529. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  92530. if (tmpVector.y < 0) {
  92531. tmpVector.scaleInPlace(-1);
  92532. }
  92533. }
  92534. else {
  92535. tmpVector.copyFrom(dragAxis);
  92536. }
  92537. if (_this.snapDistance == 0) {
  92538. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  92539. }
  92540. else {
  92541. currentSnapDragDistance += event.dragDistance;
  92542. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  92543. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  92544. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  92545. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  92546. snapped = true;
  92547. }
  92548. else {
  92549. tmpVector.scaleInPlace(0);
  92550. }
  92551. }
  92552. _this.attachedMesh.scaling.addInPlace(tmpVector);
  92553. if (snapped) {
  92554. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  92555. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  92556. }
  92557. }
  92558. });
  92559. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  92560. if (_this._customMeshSet) {
  92561. return;
  92562. }
  92563. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  92564. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  92565. _this._rootMesh.getChildMeshes().forEach(function (m) {
  92566. m.material = material;
  92567. if (m.color) {
  92568. m.color = material.emissiveColor;
  92569. }
  92570. });
  92571. });
  92572. return _this;
  92573. }
  92574. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  92575. if (this.dragBehavior) {
  92576. this.dragBehavior.enabled = value ? true : false;
  92577. }
  92578. };
  92579. /**
  92580. * Disposes of the gizmo
  92581. */
  92582. AxisScaleGizmo.prototype.dispose = function () {
  92583. this.onSnapObservable.clear();
  92584. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  92585. this.dragBehavior.detach();
  92586. _super.prototype.dispose.call(this);
  92587. };
  92588. /**
  92589. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  92590. * @param mesh The mesh to replace the default mesh of the gizmo
  92591. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  92592. */
  92593. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  92594. var _this = this;
  92595. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  92596. _super.prototype.setCustomMesh.call(this, mesh);
  92597. if (useGizmoMaterial) {
  92598. this._rootMesh.getChildMeshes().forEach(function (m) {
  92599. m.material = _this._coloredMaterial;
  92600. if (m.color) {
  92601. m.color = _this._coloredMaterial.emissiveColor;
  92602. }
  92603. });
  92604. this._customMeshSet = false;
  92605. }
  92606. };
  92607. return AxisScaleGizmo;
  92608. }(BABYLON.Gizmo));
  92609. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  92610. })(BABYLON || (BABYLON = {}));
  92611. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  92612. var BABYLON;
  92613. (function (BABYLON) {
  92614. /**
  92615. * Single plane rotation gizmo
  92616. */
  92617. var PlaneRotationGizmo = /** @class */ (function (_super) {
  92618. __extends(PlaneRotationGizmo, _super);
  92619. /**
  92620. * Creates a PlaneRotationGizmo
  92621. * @param gizmoLayer The utility layer the gizmo will be added to
  92622. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  92623. * @param color The color of the gizmo
  92624. */
  92625. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  92626. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  92627. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92628. var _this = _super.call(this, gizmoLayer) || this;
  92629. _this._pointerObserver = null;
  92630. /**
  92631. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  92632. */
  92633. _this.snapDistance = 0;
  92634. /**
  92635. * Event that fires each time the gizmo snaps to a new location.
  92636. * * snapDistance is the the change in distance
  92637. */
  92638. _this.onSnapObservable = new BABYLON.Observable();
  92639. // Create Material
  92640. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92641. coloredMaterial.disableLighting = true;
  92642. coloredMaterial.emissiveColor = color;
  92643. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92644. hoverMaterial.disableLighting = true;
  92645. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  92646. // Build mesh on root node
  92647. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92648. // Create circle out of lines
  92649. var tessellation = 20;
  92650. var radius = 0.8;
  92651. var points = new Array();
  92652. for (var i = 0; i < tessellation; i++) {
  92653. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  92654. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  92655. }
  92656. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  92657. rotationMesh.color = coloredMaterial.emissiveColor;
  92658. // Position arrow pointing in its drag axis
  92659. rotationMesh.scaling.scaleInPlace(0.26);
  92660. rotationMesh.material = coloredMaterial;
  92661. rotationMesh.rotation.x = Math.PI / 2;
  92662. parentMesh.addChild(rotationMesh);
  92663. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  92664. _this._rootMesh.addChild(parentMesh);
  92665. parentMesh.scaling.scaleInPlace(1 / 3);
  92666. // Add drag behavior to handle events when the gizmo is dragged
  92667. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  92668. _this.dragBehavior.moveAttached = false;
  92669. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  92670. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  92671. _this._rootMesh.addBehavior(_this.dragBehavior);
  92672. var lastDragPosition = new BABYLON.Vector3();
  92673. _this.dragBehavior.onDragStartObservable.add(function (e) {
  92674. if (_this.attachedMesh) {
  92675. lastDragPosition.copyFrom(e.dragPlanePoint);
  92676. }
  92677. });
  92678. var rotationMatrix = new BABYLON.Matrix();
  92679. var planeNormalTowardsCamera = new BABYLON.Vector3();
  92680. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  92681. var tmpSnapEvent = { snapDistance: 0 };
  92682. var currentSnapDragDistance = 0;
  92683. var tmpMatrix = new BABYLON.Matrix();
  92684. var tmpVector = new BABYLON.Vector3();
  92685. var amountToRotate = new BABYLON.Quaternion();
  92686. _this.dragBehavior.onDragObservable.add(function (event) {
  92687. if (_this.attachedMesh) {
  92688. if (!_this.attachedMesh.rotationQuaternion) {
  92689. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  92690. }
  92691. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  92692. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  92693. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  92694. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  92695. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  92696. var angle = Math.atan2(cross.length(), dot);
  92697. planeNormalTowardsCamera.copyFrom(planeNormal);
  92698. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  92699. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  92700. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  92701. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  92702. }
  92703. // Flip up vector depending on which side the camera is on
  92704. if (gizmoLayer.utilityLayerScene.activeCamera) {
  92705. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  92706. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  92707. planeNormalTowardsCamera.scaleInPlace(-1);
  92708. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  92709. }
  92710. }
  92711. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  92712. if (halfCircleSide)
  92713. angle = -angle;
  92714. // Snapping logic
  92715. var snapped = false;
  92716. if (_this.snapDistance != 0) {
  92717. currentSnapDragDistance += angle;
  92718. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  92719. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  92720. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  92721. angle = _this.snapDistance * dragSteps;
  92722. snapped = true;
  92723. }
  92724. else {
  92725. angle = 0;
  92726. }
  92727. }
  92728. // If the mesh has a parent, convert needed world rotation to local rotation
  92729. tmpMatrix.reset();
  92730. if (_this.attachedMesh.parent) {
  92731. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  92732. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  92733. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  92734. }
  92735. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  92736. var quaternionCoefficient = Math.sin(angle / 2);
  92737. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  92738. // 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
  92739. if (tmpMatrix.determinant() > 0) {
  92740. amountToRotate.toEulerAnglesToRef(tmpVector);
  92741. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  92742. }
  92743. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  92744. // Rotate selected mesh quaternion over fixed axis
  92745. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  92746. }
  92747. else {
  92748. // Rotate selected mesh quaternion over rotated axis
  92749. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  92750. }
  92751. lastDragPosition.copyFrom(event.dragPlanePoint);
  92752. if (snapped) {
  92753. tmpSnapEvent.snapDistance = angle;
  92754. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  92755. }
  92756. }
  92757. });
  92758. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  92759. if (_this._customMeshSet) {
  92760. return;
  92761. }
  92762. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  92763. var material = isHovered ? hoverMaterial : coloredMaterial;
  92764. _this._rootMesh.getChildMeshes().forEach(function (m) {
  92765. m.material = material;
  92766. if (m.color) {
  92767. m.color = material.emissiveColor;
  92768. }
  92769. });
  92770. });
  92771. return _this;
  92772. }
  92773. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  92774. if (this.dragBehavior) {
  92775. this.dragBehavior.enabled = value ? true : false;
  92776. }
  92777. };
  92778. /**
  92779. * Disposes of the gizmo
  92780. */
  92781. PlaneRotationGizmo.prototype.dispose = function () {
  92782. this.onSnapObservable.clear();
  92783. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  92784. this.dragBehavior.detach();
  92785. _super.prototype.dispose.call(this);
  92786. };
  92787. return PlaneRotationGizmo;
  92788. }(BABYLON.Gizmo));
  92789. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  92790. })(BABYLON || (BABYLON = {}));
  92791. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  92792. var BABYLON;
  92793. (function (BABYLON) {
  92794. /**
  92795. * Gizmo that enables dragging a mesh along 3 axis
  92796. */
  92797. var PositionGizmo = /** @class */ (function (_super) {
  92798. __extends(PositionGizmo, _super);
  92799. /**
  92800. * Creates a PositionGizmo
  92801. * @param gizmoLayer The utility layer the gizmo will be added to
  92802. */
  92803. function PositionGizmo(gizmoLayer) {
  92804. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92805. var _this = _super.call(this, gizmoLayer) || this;
  92806. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  92807. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  92808. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  92809. _this.attachedMesh = null;
  92810. return _this;
  92811. }
  92812. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  92813. set: function (mesh) {
  92814. if (this.xGizmo) {
  92815. this.xGizmo.attachedMesh = mesh;
  92816. this.yGizmo.attachedMesh = mesh;
  92817. this.zGizmo.attachedMesh = mesh;
  92818. }
  92819. },
  92820. enumerable: true,
  92821. configurable: true
  92822. });
  92823. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  92824. get: function () {
  92825. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  92826. },
  92827. set: function (value) {
  92828. if (this.xGizmo) {
  92829. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92830. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92831. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92832. }
  92833. },
  92834. enumerable: true,
  92835. configurable: true
  92836. });
  92837. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  92838. get: function () {
  92839. return this.xGizmo.snapDistance;
  92840. },
  92841. /**
  92842. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92843. */
  92844. set: function (value) {
  92845. if (this.xGizmo) {
  92846. this.xGizmo.snapDistance = value;
  92847. this.yGizmo.snapDistance = value;
  92848. this.zGizmo.snapDistance = value;
  92849. }
  92850. },
  92851. enumerable: true,
  92852. configurable: true
  92853. });
  92854. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  92855. get: function () {
  92856. return this.xGizmo.scaleRatio;
  92857. },
  92858. /**
  92859. * Ratio for the scale of the gizmo (Default: 1)
  92860. */
  92861. set: function (value) {
  92862. if (this.xGizmo) {
  92863. this.xGizmo.scaleRatio = value;
  92864. this.yGizmo.scaleRatio = value;
  92865. this.zGizmo.scaleRatio = value;
  92866. }
  92867. },
  92868. enumerable: true,
  92869. configurable: true
  92870. });
  92871. /**
  92872. * Disposes of the gizmo
  92873. */
  92874. PositionGizmo.prototype.dispose = function () {
  92875. this.xGizmo.dispose();
  92876. this.yGizmo.dispose();
  92877. this.zGizmo.dispose();
  92878. };
  92879. /**
  92880. * CustomMeshes are not supported by this gizmo
  92881. * @param mesh The mesh to replace the default mesh of the gizmo
  92882. */
  92883. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  92884. 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)");
  92885. };
  92886. return PositionGizmo;
  92887. }(BABYLON.Gizmo));
  92888. BABYLON.PositionGizmo = PositionGizmo;
  92889. })(BABYLON || (BABYLON = {}));
  92890. //# sourceMappingURL=babylon.positionGizmo.js.map
  92891. var BABYLON;
  92892. (function (BABYLON) {
  92893. /**
  92894. * Gizmo that enables rotating a mesh along 3 axis
  92895. */
  92896. var RotationGizmo = /** @class */ (function (_super) {
  92897. __extends(RotationGizmo, _super);
  92898. /**
  92899. * Creates a RotationGizmo
  92900. * @param gizmoLayer The utility layer the gizmo will be added to
  92901. */
  92902. function RotationGizmo(gizmoLayer) {
  92903. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92904. var _this = _super.call(this, gizmoLayer) || this;
  92905. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  92906. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  92907. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  92908. _this.attachedMesh = null;
  92909. return _this;
  92910. }
  92911. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  92912. set: function (mesh) {
  92913. if (this.xGizmo) {
  92914. this.xGizmo.attachedMesh = mesh;
  92915. this.yGizmo.attachedMesh = mesh;
  92916. this.zGizmo.attachedMesh = mesh;
  92917. }
  92918. },
  92919. enumerable: true,
  92920. configurable: true
  92921. });
  92922. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  92923. get: function () {
  92924. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  92925. },
  92926. set: function (value) {
  92927. if (this.xGizmo) {
  92928. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92929. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92930. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92931. }
  92932. },
  92933. enumerable: true,
  92934. configurable: true
  92935. });
  92936. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  92937. get: function () {
  92938. return this.xGizmo.snapDistance;
  92939. },
  92940. /**
  92941. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92942. */
  92943. set: function (value) {
  92944. if (this.xGizmo) {
  92945. this.xGizmo.snapDistance = value;
  92946. this.yGizmo.snapDistance = value;
  92947. this.zGizmo.snapDistance = value;
  92948. }
  92949. },
  92950. enumerable: true,
  92951. configurable: true
  92952. });
  92953. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  92954. get: function () {
  92955. return this.xGizmo.scaleRatio;
  92956. },
  92957. /**
  92958. * Ratio for the scale of the gizmo (Default: 1)
  92959. */
  92960. set: function (value) {
  92961. if (this.xGizmo) {
  92962. this.xGizmo.scaleRatio = value;
  92963. this.yGizmo.scaleRatio = value;
  92964. this.zGizmo.scaleRatio = value;
  92965. }
  92966. },
  92967. enumerable: true,
  92968. configurable: true
  92969. });
  92970. /**
  92971. * Disposes of the gizmo
  92972. */
  92973. RotationGizmo.prototype.dispose = function () {
  92974. this.xGizmo.dispose();
  92975. this.yGizmo.dispose();
  92976. this.zGizmo.dispose();
  92977. };
  92978. /**
  92979. * CustomMeshes are not supported by this gizmo
  92980. * @param mesh The mesh to replace the default mesh of the gizmo
  92981. */
  92982. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  92983. 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)");
  92984. };
  92985. return RotationGizmo;
  92986. }(BABYLON.Gizmo));
  92987. BABYLON.RotationGizmo = RotationGizmo;
  92988. })(BABYLON || (BABYLON = {}));
  92989. //# sourceMappingURL=babylon.rotationGizmo.js.map
  92990. var BABYLON;
  92991. (function (BABYLON) {
  92992. /**
  92993. * Gizmo that enables scaling a mesh along 3 axis
  92994. */
  92995. var ScaleGizmo = /** @class */ (function (_super) {
  92996. __extends(ScaleGizmo, _super);
  92997. /**
  92998. * Creates a ScaleGizmo
  92999. * @param gizmoLayer The utility layer the gizmo will be added to
  93000. */
  93001. function ScaleGizmo(gizmoLayer) {
  93002. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93003. var _this = _super.call(this, gizmoLayer) || this;
  93004. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  93005. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  93006. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  93007. // Create uniform scale gizmo
  93008. _this._uniformGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  93009. _this._uniformGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  93010. _this._uniformGizmo.uniformScaling = true;
  93011. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this._uniformGizmo.gizmoLayer.utilityLayerScene);
  93012. octahedron.scaling.scaleInPlace(0.007);
  93013. _this._uniformGizmo.setCustomMesh(octahedron, true);
  93014. _this.attachedMesh = null;
  93015. return _this;
  93016. }
  93017. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  93018. set: function (mesh) {
  93019. if (this.xGizmo) {
  93020. this.xGizmo.attachedMesh = mesh;
  93021. this.yGizmo.attachedMesh = mesh;
  93022. this.zGizmo.attachedMesh = mesh;
  93023. this._uniformGizmo.attachedMesh = mesh;
  93024. }
  93025. },
  93026. enumerable: true,
  93027. configurable: true
  93028. });
  93029. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  93030. get: function () {
  93031. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  93032. },
  93033. set: function (value) {
  93034. if (this.xGizmo) {
  93035. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93036. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93037. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93038. }
  93039. },
  93040. enumerable: true,
  93041. configurable: true
  93042. });
  93043. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  93044. get: function () {
  93045. return this.xGizmo.snapDistance;
  93046. },
  93047. /**
  93048. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  93049. */
  93050. set: function (value) {
  93051. if (this.xGizmo) {
  93052. this.xGizmo.snapDistance = value;
  93053. this.yGizmo.snapDistance = value;
  93054. this.zGizmo.snapDistance = value;
  93055. this._uniformGizmo.snapDistance = value;
  93056. }
  93057. },
  93058. enumerable: true,
  93059. configurable: true
  93060. });
  93061. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  93062. get: function () {
  93063. return this.xGizmo.scaleRatio;
  93064. },
  93065. /**
  93066. * Ratio for the scale of the gizmo (Default: 1)
  93067. */
  93068. set: function (value) {
  93069. if (this.xGizmo) {
  93070. this.xGizmo.scaleRatio = value;
  93071. this.yGizmo.scaleRatio = value;
  93072. this.zGizmo.scaleRatio = value;
  93073. this._uniformGizmo.scaleRatio = value;
  93074. }
  93075. },
  93076. enumerable: true,
  93077. configurable: true
  93078. });
  93079. /**
  93080. * Disposes of the gizmo
  93081. */
  93082. ScaleGizmo.prototype.dispose = function () {
  93083. this.xGizmo.dispose();
  93084. this.yGizmo.dispose();
  93085. this.zGizmo.dispose();
  93086. this._uniformGizmo.dispose();
  93087. };
  93088. return ScaleGizmo;
  93089. }(BABYLON.Gizmo));
  93090. BABYLON.ScaleGizmo = ScaleGizmo;
  93091. })(BABYLON || (BABYLON = {}));
  93092. //# sourceMappingURL=babylon.scaleGizmo.js.map
  93093. var BABYLON;
  93094. (function (BABYLON) {
  93095. /**
  93096. * Bounding box gizmo
  93097. */
  93098. var BoundingBoxGizmo = /** @class */ (function (_super) {
  93099. __extends(BoundingBoxGizmo, _super);
  93100. /**
  93101. * Creates an BoundingBoxGizmo
  93102. * @param gizmoLayer The utility layer the gizmo will be added to
  93103. * @param color The color of the gizmo
  93104. */
  93105. function BoundingBoxGizmo(color, gizmoLayer) {
  93106. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  93107. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  93108. var _this = _super.call(this, gizmoLayer) || this;
  93109. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  93110. _this._renderObserver = null;
  93111. _this._pointerObserver = null;
  93112. _this._scaleDragSpeed = 0.2;
  93113. _this._tmpQuaternion = new BABYLON.Quaternion();
  93114. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  93115. _this._tmpRotationMatrix = new BABYLON.Matrix();
  93116. /**
  93117. * 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)
  93118. */
  93119. _this.ignoreChildren = false;
  93120. /**
  93121. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  93122. */
  93123. _this.rotationSphereSize = 0.1;
  93124. /**
  93125. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  93126. */
  93127. _this.scaleBoxSize = 0.1;
  93128. /**
  93129. * 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)
  93130. */
  93131. _this.fixedDragMeshScreenSize = false;
  93132. /**
  93133. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  93134. */
  93135. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  93136. /**
  93137. * Fired when a rotation sphere or scale box is dragged
  93138. */
  93139. _this.onDragStartObservable = new BABYLON.Observable();
  93140. /**
  93141. * Fired when a scale box is dragged
  93142. */
  93143. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  93144. /**
  93145. * Fired when a scale box drag is ended
  93146. */
  93147. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  93148. /**
  93149. * Fired when a rotation sphere is dragged
  93150. */
  93151. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  93152. /**
  93153. * Fired when a rotation sphere drag is ended
  93154. */
  93155. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  93156. /**
  93157. * 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)
  93158. */
  93159. _this.scalePivot = null;
  93160. _this._existingMeshScale = new BABYLON.Vector3();
  93161. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  93162. // store/remove pivot point should only be applied during their outermost calls
  93163. _this._pivotCached = 0;
  93164. _this._oldPivotPoint = new BABYLON.Vector3();
  93165. _this._pivotTranslation = new BABYLON.Vector3();
  93166. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  93167. _this._updateScale = false;
  93168. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  93169. // Create Materials
  93170. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93171. coloredMaterial.disableLighting = true;
  93172. coloredMaterial.emissiveColor = color;
  93173. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93174. hoverColoredMaterial.disableLighting = true;
  93175. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  93176. // Build bounding box out of lines
  93177. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93178. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  93179. var lines = [];
  93180. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  93181. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  93182. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  93183. 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));
  93184. 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));
  93185. 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));
  93186. 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));
  93187. 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));
  93188. 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));
  93189. 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));
  93190. 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));
  93191. 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));
  93192. lines.forEach(function (l) {
  93193. l.color = color;
  93194. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  93195. l.isPickable = false;
  93196. _this._lineBoundingBox.addChild(l);
  93197. });
  93198. _this._rootMesh.addChild(_this._lineBoundingBox);
  93199. // Create rotation spheres
  93200. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93201. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  93202. var _loop_1 = function (i_1) {
  93203. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  93204. sphere.rotationQuaternion = new BABYLON.Quaternion();
  93205. sphere.material = coloredMaterial;
  93206. // Drag behavior
  93207. _dragBehavior = new BABYLON.PointerDragBehavior({});
  93208. _dragBehavior.moveAttached = false;
  93209. _dragBehavior.updateDragPlane = false;
  93210. sphere.addBehavior(_dragBehavior);
  93211. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  93212. var totalTurnAmountOfDrag = 0;
  93213. _dragBehavior.onDragStartObservable.add(function (event) {
  93214. startingTurnDirection.copyFrom(sphere.forward);
  93215. totalTurnAmountOfDrag = 0;
  93216. });
  93217. _dragBehavior.onDragObservable.add(function (event) {
  93218. _this.onRotationSphereDragObservable.notifyObservers({});
  93219. if (_this.attachedMesh) {
  93220. _this._removeAndStorePivotPoint();
  93221. var worldDragDirection = startingTurnDirection;
  93222. // Project the world right on to the drag plane
  93223. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  93224. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  93225. // project drag delta on to the resulting drag axis and rotate based on that
  93226. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  93227. // Make rotation relative to size of mesh.
  93228. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  93229. // Rotate based on axis
  93230. if (!_this.attachedMesh.rotationQuaternion) {
  93231. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  93232. }
  93233. if (!_this._anchorMesh.rotationQuaternion) {
  93234. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  93235. }
  93236. // Do not allow the object to turn more than a full circle
  93237. totalTurnAmountOfDrag += projectDist;
  93238. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  93239. if (i_1 >= 8) {
  93240. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  93241. }
  93242. else if (i_1 >= 4) {
  93243. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  93244. }
  93245. else {
  93246. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  93247. }
  93248. // Rotate around center of bounding box
  93249. _this._anchorMesh.addChild(_this.attachedMesh);
  93250. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  93251. _this._anchorMesh.removeChild(_this.attachedMesh);
  93252. }
  93253. _this.updateBoundingBox();
  93254. _this._restorePivotPoint();
  93255. }
  93256. });
  93257. // Selection/deselection
  93258. _dragBehavior.onDragStartObservable.add(function () {
  93259. _this.onDragStartObservable.notifyObservers({});
  93260. _this._selectNode(sphere);
  93261. });
  93262. _dragBehavior.onDragEndObservable.add(function () {
  93263. _this.onRotationSphereDragEndObservable.notifyObservers({});
  93264. _this._selectNode(null);
  93265. });
  93266. this_1._rotateSpheresParent.addChild(sphere);
  93267. };
  93268. var this_1 = this, _dragBehavior;
  93269. for (var i_1 = 0; i_1 < 12; i_1++) {
  93270. _loop_1(i_1);
  93271. }
  93272. _this._rootMesh.addChild(_this._rotateSpheresParent);
  93273. // Create scale cubes
  93274. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93275. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  93276. for (var i = 0; i < 2; i++) {
  93277. for (var j = 0; j < 2; j++) {
  93278. var _loop_2 = function () {
  93279. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  93280. box.material = coloredMaterial;
  93281. // Dragging logic
  93282. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  93283. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  93284. _dragBehavior.moveAttached = false;
  93285. box.addBehavior(_dragBehavior);
  93286. _dragBehavior.onDragObservable.add(function (event) {
  93287. _this.onScaleBoxDragObservable.notifyObservers({});
  93288. if (_this.attachedMesh) {
  93289. _this._removeAndStorePivotPoint();
  93290. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  93291. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  93292. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  93293. _this.updateBoundingBox();
  93294. if (_this.scalePivot) {
  93295. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  93296. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  93297. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  93298. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  93299. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  93300. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  93301. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  93302. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  93303. }
  93304. else {
  93305. // Scale from the position of the opposite corner
  93306. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  93307. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  93308. }
  93309. _this._anchorMesh.addChild(_this.attachedMesh);
  93310. _this._anchorMesh.scaling.addInPlace(deltaScale);
  93311. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  93312. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  93313. }
  93314. _this._anchorMesh.removeChild(_this.attachedMesh);
  93315. _this._restorePivotPoint();
  93316. }
  93317. });
  93318. // Selection/deselection
  93319. _dragBehavior.onDragStartObservable.add(function () {
  93320. _this.onDragStartObservable.notifyObservers({});
  93321. _this._selectNode(box);
  93322. });
  93323. _dragBehavior.onDragEndObservable.add(function () {
  93324. _this.onScaleBoxDragEndObservable.notifyObservers({});
  93325. _this._selectNode(null);
  93326. });
  93327. this_2._scaleBoxesParent.addChild(box);
  93328. };
  93329. var this_2 = this, _dragBehavior;
  93330. for (var k = 0; k < 2; k++) {
  93331. _loop_2();
  93332. }
  93333. }
  93334. }
  93335. _this._rootMesh.addChild(_this._scaleBoxesParent);
  93336. // Hover color change
  93337. var pointerIds = new Array();
  93338. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  93339. if (!pointerIds[pointerInfo.event.pointerId]) {
  93340. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  93341. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  93342. pointerIds[pointerInfo.event.pointerId] = mesh;
  93343. mesh.material = hoverColoredMaterial;
  93344. }
  93345. });
  93346. }
  93347. else {
  93348. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  93349. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  93350. delete pointerIds[pointerInfo.event.pointerId];
  93351. }
  93352. }
  93353. });
  93354. // Update bounding box positions
  93355. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  93356. // Only update the bouding box if scaling has changed
  93357. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  93358. _this.updateBoundingBox();
  93359. }
  93360. });
  93361. _this.updateBoundingBox();
  93362. return _this;
  93363. }
  93364. BoundingBoxGizmo.prototype._removeAndStorePivotPoint = function () {
  93365. if (this.attachedMesh && this._pivotCached === 0) {
  93366. // Save old pivot and set pivot to 0,0,0
  93367. this.attachedMesh.getPivotPointToRef(this._oldPivotPoint);
  93368. if (this._oldPivotPoint.equalsToFloats(0, 0, 0)) {
  93369. return;
  93370. }
  93371. this.attachedMesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  93372. this._oldPivotPoint.subtractToRef(this.attachedMesh.getPivotPoint(), this._pivotTranslation);
  93373. this._tmpVector.copyFromFloats(1, 1, 1);
  93374. this._tmpVector.subtractInPlace(this.attachedMesh.scaling);
  93375. this._tmpVector.multiplyInPlace(this._pivotTranslation);
  93376. this.attachedMesh.position.addInPlace(this._tmpVector);
  93377. }
  93378. this._pivotCached++;
  93379. };
  93380. BoundingBoxGizmo.prototype._restorePivotPoint = function () {
  93381. if (this.attachedMesh && !this._oldPivotPoint.equalsToFloats(0, 0, 0) && this._pivotCached === 1) {
  93382. this.attachedMesh.setPivotPoint(this._oldPivotPoint);
  93383. this._tmpVector.copyFromFloats(1, 1, 1);
  93384. this._tmpVector.subtractInPlace(this.attachedMesh.scaling);
  93385. this._tmpVector.multiplyInPlace(this._pivotTranslation);
  93386. this.attachedMesh.position.subtractInPlace(this._tmpVector);
  93387. }
  93388. this._pivotCached--;
  93389. };
  93390. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  93391. if (value) {
  93392. // Reset anchor mesh to match attached mesh's scale
  93393. // This is needed to avoid invalid box/sphere position on first drag
  93394. this._removeAndStorePivotPoint();
  93395. this._anchorMesh.addChild(value);
  93396. this._anchorMesh.removeChild(value);
  93397. this._restorePivotPoint();
  93398. this.updateBoundingBox();
  93399. }
  93400. };
  93401. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  93402. this._rotateSpheresParent.getChildMeshes()
  93403. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  93404. m.isVisible = (!selectedMesh || m == selectedMesh);
  93405. });
  93406. };
  93407. BoundingBoxGizmo.prototype._recurseComputeWorld = function (node) {
  93408. var _this = this;
  93409. node.computeWorldMatrix(true);
  93410. if (!this.ignoreChildren) {
  93411. node.getDescendants().forEach(function (n) {
  93412. _this._recurseComputeWorld(n);
  93413. });
  93414. }
  93415. };
  93416. /**
  93417. * Updates the bounding box information for the Gizmo
  93418. */
  93419. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  93420. if (this.attachedMesh) {
  93421. this._removeAndStorePivotPoint();
  93422. this._update();
  93423. // Rotate based on axis
  93424. if (!this.attachedMesh.rotationQuaternion) {
  93425. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  93426. }
  93427. if (!this._anchorMesh.rotationQuaternion) {
  93428. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  93429. }
  93430. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  93431. // Store original position and reset mesh to origin before computing the bounding box
  93432. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  93433. this._tmpVector.copyFrom(this.attachedMesh.position);
  93434. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  93435. this.attachedMesh.position.set(0, 0, 0);
  93436. // Update bounding dimensions/positions
  93437. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren);
  93438. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  93439. // Update gizmo to match bounding box scaling and rotation
  93440. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  93441. 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);
  93442. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  93443. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  93444. this._lineBoundingBox.computeWorldMatrix();
  93445. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  93446. // restore position/rotation values
  93447. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  93448. this.attachedMesh.position.copyFrom(this._tmpVector);
  93449. this._recurseComputeWorld(this.attachedMesh);
  93450. }
  93451. // Update rotation sphere locations
  93452. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  93453. for (var i = 0; i < 3; i++) {
  93454. for (var j = 0; j < 2; j++) {
  93455. for (var k = 0; k < 2; k++) {
  93456. var index = ((i * 4) + (j * 2)) + k;
  93457. if (i == 0) {
  93458. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  93459. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  93460. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  93461. }
  93462. if (i == 1) {
  93463. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  93464. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  93465. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  93466. }
  93467. if (i == 2) {
  93468. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  93469. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  93470. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  93471. }
  93472. if (this.fixedDragMeshScreenSize) {
  93473. this._rootMesh.computeWorldMatrix();
  93474. this._rotateSpheresParent.computeWorldMatrix();
  93475. rotateSpheres[index].computeWorldMatrix();
  93476. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  93477. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  93478. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  93479. }
  93480. else {
  93481. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  93482. }
  93483. }
  93484. }
  93485. }
  93486. // Update scale box locations
  93487. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  93488. for (var i = 0; i < 2; i++) {
  93489. for (var j = 0; j < 2; j++) {
  93490. for (var k = 0; k < 2; k++) {
  93491. var index = ((i * 4) + (j * 2)) + k;
  93492. if (scaleBoxes[index]) {
  93493. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  93494. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  93495. if (this.fixedDragMeshScreenSize) {
  93496. this._rootMesh.computeWorldMatrix();
  93497. this._scaleBoxesParent.computeWorldMatrix();
  93498. scaleBoxes[index].computeWorldMatrix();
  93499. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  93500. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  93501. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  93502. }
  93503. else {
  93504. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  93505. }
  93506. }
  93507. }
  93508. }
  93509. }
  93510. if (this.attachedMesh) {
  93511. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  93512. this._restorePivotPoint();
  93513. }
  93514. };
  93515. /**
  93516. * Enables rotation on the specified axis and disables rotation on the others
  93517. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  93518. */
  93519. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  93520. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  93521. if (i < 4) {
  93522. m.setEnabled(axis.indexOf("x") != -1);
  93523. }
  93524. else if (i < 8) {
  93525. m.setEnabled(axis.indexOf("y") != -1);
  93526. }
  93527. else {
  93528. m.setEnabled(axis.indexOf("z") != -1);
  93529. }
  93530. });
  93531. };
  93532. /**
  93533. * Disposes of the gizmo
  93534. */
  93535. BoundingBoxGizmo.prototype.dispose = function () {
  93536. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  93537. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  93538. this._lineBoundingBox.dispose();
  93539. this._rotateSpheresParent.dispose();
  93540. this._scaleBoxesParent.dispose();
  93541. _super.prototype.dispose.call(this);
  93542. };
  93543. /**
  93544. * 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)
  93545. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  93546. * @returns the bounding box mesh with the passed in mesh as a child
  93547. */
  93548. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  93549. var makeNotPickable = function (root) {
  93550. root.isPickable = false;
  93551. root.getChildMeshes().forEach(function (c) {
  93552. makeNotPickable(c);
  93553. });
  93554. };
  93555. makeNotPickable(mesh);
  93556. // Reset position to get boudning box from origin with no rotation
  93557. if (!mesh.rotationQuaternion) {
  93558. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  93559. }
  93560. var oldPos = mesh.position.clone();
  93561. var oldRot = mesh.rotationQuaternion.clone();
  93562. mesh.rotationQuaternion.set(0, 0, 0, 1);
  93563. mesh.position.set(0, 0, 0);
  93564. // Update bounding dimensions/positions
  93565. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  93566. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  93567. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  93568. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  93569. // Restore original positions
  93570. mesh.addChild(box);
  93571. mesh.rotationQuaternion.copyFrom(oldRot);
  93572. mesh.position.copyFrom(oldPos);
  93573. // Reverse parenting
  93574. mesh.removeChild(box);
  93575. box.addChild(mesh);
  93576. box.visibility = 0;
  93577. return box;
  93578. };
  93579. /**
  93580. * CustomMeshes are not supported by this gizmo
  93581. * @param mesh The mesh to replace the default mesh of the gizmo
  93582. */
  93583. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  93584. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  93585. };
  93586. return BoundingBoxGizmo;
  93587. }(BABYLON.Gizmo));
  93588. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  93589. })(BABYLON || (BABYLON = {}));
  93590. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  93591. var BABYLON;
  93592. (function (BABYLON) {
  93593. /**
  93594. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  93595. */
  93596. var GizmoManager = /** @class */ (function () {
  93597. /**
  93598. * Instatiates a gizmo manager
  93599. * @param scene the scene to overlay the gizmos on top of
  93600. */
  93601. function GizmoManager(scene) {
  93602. var _this = this;
  93603. this.scene = scene;
  93604. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  93605. this._pointerObserver = null;
  93606. this._attachedMesh = null;
  93607. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  93608. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  93609. /**
  93610. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  93611. */
  93612. this.attachableMeshes = null;
  93613. /**
  93614. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  93615. */
  93616. this.usePointerToAttachGizmos = true;
  93617. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  93618. // Instatiate/dispose gizmos based on pointer actions
  93619. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  93620. if (!_this.usePointerToAttachGizmos) {
  93621. return;
  93622. }
  93623. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  93624. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  93625. var node = pointerInfo.pickInfo.pickedMesh;
  93626. if (_this.attachableMeshes == null) {
  93627. // Attach to the most parent node
  93628. while (node && node.parent != null) {
  93629. node = node.parent;
  93630. }
  93631. }
  93632. else {
  93633. // Attach to the parent node that is an attachableMesh
  93634. var found = false;
  93635. _this.attachableMeshes.forEach(function (mesh) {
  93636. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  93637. node = mesh;
  93638. found = true;
  93639. }
  93640. });
  93641. if (!found) {
  93642. node = null;
  93643. }
  93644. }
  93645. if (node instanceof BABYLON.AbstractMesh) {
  93646. _this.attachToMesh(node);
  93647. }
  93648. else {
  93649. _this.attachToMesh(null);
  93650. }
  93651. }
  93652. else {
  93653. _this.attachToMesh(null);
  93654. }
  93655. }
  93656. });
  93657. }
  93658. /**
  93659. * Attaches a set of gizmos to the specified mesh
  93660. * @param mesh The mesh the gizmo's should be attached to
  93661. */
  93662. GizmoManager.prototype.attachToMesh = function (mesh) {
  93663. if (this._attachedMesh) {
  93664. this._attachedMesh.removeBehavior(this._dragBehavior);
  93665. }
  93666. this._attachedMesh = mesh;
  93667. for (var key in this.gizmos) {
  93668. var gizmo = (this.gizmos[key]);
  93669. if (gizmo && this._gizmosEnabled[key]) {
  93670. gizmo.attachedMesh = mesh;
  93671. }
  93672. }
  93673. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  93674. this._attachedMesh.addBehavior(this._dragBehavior);
  93675. }
  93676. };
  93677. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  93678. get: function () {
  93679. return this._gizmosEnabled.positionGizmo;
  93680. },
  93681. /**
  93682. * If the position gizmo is enabled
  93683. */
  93684. set: function (value) {
  93685. if (value) {
  93686. if (!this.gizmos.positionGizmo) {
  93687. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  93688. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  93689. }
  93690. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  93691. }
  93692. else if (this.gizmos.positionGizmo) {
  93693. this.gizmos.positionGizmo.attachedMesh = null;
  93694. }
  93695. this._gizmosEnabled.positionGizmo = value;
  93696. },
  93697. enumerable: true,
  93698. configurable: true
  93699. });
  93700. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  93701. get: function () {
  93702. return this._gizmosEnabled.rotationGizmo;
  93703. },
  93704. /**
  93705. * If the rotation gizmo is enabled
  93706. */
  93707. set: function (value) {
  93708. if (value) {
  93709. if (!this.gizmos.rotationGizmo) {
  93710. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  93711. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  93712. }
  93713. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  93714. }
  93715. else if (this.gizmos.rotationGizmo) {
  93716. this.gizmos.rotationGizmo.attachedMesh = null;
  93717. }
  93718. this._gizmosEnabled.rotationGizmo = value;
  93719. },
  93720. enumerable: true,
  93721. configurable: true
  93722. });
  93723. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  93724. get: function () {
  93725. return this._gizmosEnabled.scaleGizmo;
  93726. },
  93727. /**
  93728. * If the scale gizmo is enabled
  93729. */
  93730. set: function (value) {
  93731. if (value) {
  93732. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  93733. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  93734. }
  93735. else if (this.gizmos.scaleGizmo) {
  93736. this.gizmos.scaleGizmo.attachedMesh = null;
  93737. }
  93738. this._gizmosEnabled.scaleGizmo = value;
  93739. },
  93740. enumerable: true,
  93741. configurable: true
  93742. });
  93743. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  93744. get: function () {
  93745. return this._gizmosEnabled.boundingBoxGizmo;
  93746. },
  93747. /**
  93748. * If the boundingBox gizmo is enabled
  93749. */
  93750. set: function (value) {
  93751. if (value) {
  93752. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  93753. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  93754. if (this._attachedMesh) {
  93755. this._attachedMesh.removeBehavior(this._dragBehavior);
  93756. this._attachedMesh.addBehavior(this._dragBehavior);
  93757. }
  93758. }
  93759. else if (this.gizmos.boundingBoxGizmo) {
  93760. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  93761. }
  93762. this._gizmosEnabled.boundingBoxGizmo = value;
  93763. },
  93764. enumerable: true,
  93765. configurable: true
  93766. });
  93767. /**
  93768. * Disposes of the gizmo manager
  93769. */
  93770. GizmoManager.prototype.dispose = function () {
  93771. this.scene.onPointerObservable.remove(this._pointerObserver);
  93772. for (var key in this.gizmos) {
  93773. var gizmo = (this.gizmos[key]);
  93774. if (gizmo) {
  93775. gizmo.dispose();
  93776. }
  93777. }
  93778. this._dragBehavior.detach();
  93779. };
  93780. return GizmoManager;
  93781. }());
  93782. BABYLON.GizmoManager = GizmoManager;
  93783. })(BABYLON || (BABYLON = {}));
  93784. //# sourceMappingURL=babylon.gizmoManager.js.map
  93785. var BABYLON;
  93786. (function (BABYLON) {
  93787. /**
  93788. * Defines a target to use with MorphTargetManager
  93789. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  93790. */
  93791. var MorphTarget = /** @class */ (function () {
  93792. /**
  93793. * Creates a new MorphTarget
  93794. * @param name defines the name of the target
  93795. * @param influence defines the influence to use
  93796. */
  93797. function MorphTarget(
  93798. /** defines the name of the target */
  93799. name, influence, scene) {
  93800. if (influence === void 0) { influence = 0; }
  93801. if (scene === void 0) { scene = null; }
  93802. this.name = name;
  93803. /**
  93804. * Gets or sets the list of animations
  93805. */
  93806. this.animations = new Array();
  93807. this._positions = null;
  93808. this._normals = null;
  93809. this._tangents = null;
  93810. /**
  93811. * Observable raised when the influence changes
  93812. */
  93813. this.onInfluenceChanged = new BABYLON.Observable();
  93814. this._animationPropertiesOverride = null;
  93815. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93816. this.influence = influence;
  93817. }
  93818. Object.defineProperty(MorphTarget.prototype, "influence", {
  93819. /**
  93820. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  93821. */
  93822. get: function () {
  93823. return this._influence;
  93824. },
  93825. set: function (influence) {
  93826. if (this._influence === influence) {
  93827. return;
  93828. }
  93829. var previous = this._influence;
  93830. this._influence = influence;
  93831. if (this.onInfluenceChanged.hasObservers) {
  93832. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  93833. }
  93834. },
  93835. enumerable: true,
  93836. configurable: true
  93837. });
  93838. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  93839. /**
  93840. * Gets or sets the animation properties override
  93841. */
  93842. get: function () {
  93843. if (!this._animationPropertiesOverride && this._scene) {
  93844. return this._scene.animationPropertiesOverride;
  93845. }
  93846. return this._animationPropertiesOverride;
  93847. },
  93848. set: function (value) {
  93849. this._animationPropertiesOverride = value;
  93850. },
  93851. enumerable: true,
  93852. configurable: true
  93853. });
  93854. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  93855. /**
  93856. * Gets a boolean defining if the target contains position data
  93857. */
  93858. get: function () {
  93859. return !!this._positions;
  93860. },
  93861. enumerable: true,
  93862. configurable: true
  93863. });
  93864. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  93865. /**
  93866. * Gets a boolean defining if the target contains normal data
  93867. */
  93868. get: function () {
  93869. return !!this._normals;
  93870. },
  93871. enumerable: true,
  93872. configurable: true
  93873. });
  93874. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  93875. /**
  93876. * Gets a boolean defining if the target contains tangent data
  93877. */
  93878. get: function () {
  93879. return !!this._tangents;
  93880. },
  93881. enumerable: true,
  93882. configurable: true
  93883. });
  93884. /**
  93885. * Affects position data to this target
  93886. * @param data defines the position data to use
  93887. */
  93888. MorphTarget.prototype.setPositions = function (data) {
  93889. this._positions = data;
  93890. };
  93891. /**
  93892. * Gets the position data stored in this target
  93893. * @returns a FloatArray containing the position data (or null if not present)
  93894. */
  93895. MorphTarget.prototype.getPositions = function () {
  93896. return this._positions;
  93897. };
  93898. /**
  93899. * Affects normal data to this target
  93900. * @param data defines the normal data to use
  93901. */
  93902. MorphTarget.prototype.setNormals = function (data) {
  93903. this._normals = data;
  93904. };
  93905. /**
  93906. * Gets the normal data stored in this target
  93907. * @returns a FloatArray containing the normal data (or null if not present)
  93908. */
  93909. MorphTarget.prototype.getNormals = function () {
  93910. return this._normals;
  93911. };
  93912. /**
  93913. * Affects tangent data to this target
  93914. * @param data defines the tangent data to use
  93915. */
  93916. MorphTarget.prototype.setTangents = function (data) {
  93917. this._tangents = data;
  93918. };
  93919. /**
  93920. * Gets the tangent data stored in this target
  93921. * @returns a FloatArray containing the tangent data (or null if not present)
  93922. */
  93923. MorphTarget.prototype.getTangents = function () {
  93924. return this._tangents;
  93925. };
  93926. /**
  93927. * Serializes the current target into a Serialization object
  93928. * @returns the serialized object
  93929. */
  93930. MorphTarget.prototype.serialize = function () {
  93931. var serializationObject = {};
  93932. serializationObject.name = this.name;
  93933. serializationObject.influence = this.influence;
  93934. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  93935. if (this.hasNormals) {
  93936. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  93937. }
  93938. if (this.hasTangents) {
  93939. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  93940. }
  93941. // Animations
  93942. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  93943. return serializationObject;
  93944. };
  93945. // Statics
  93946. /**
  93947. * Creates a new target from serialized data
  93948. * @param serializationObject defines the serialized data to use
  93949. * @returns a new MorphTarget
  93950. */
  93951. MorphTarget.Parse = function (serializationObject) {
  93952. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  93953. result.setPositions(serializationObject.positions);
  93954. if (serializationObject.normals) {
  93955. result.setNormals(serializationObject.normals);
  93956. }
  93957. if (serializationObject.tangents) {
  93958. result.setTangents(serializationObject.tangents);
  93959. }
  93960. // Animations
  93961. if (serializationObject.animations) {
  93962. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  93963. var parsedAnimation = serializationObject.animations[animationIndex];
  93964. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  93965. }
  93966. }
  93967. return result;
  93968. };
  93969. /**
  93970. * Creates a MorphTarget from mesh data
  93971. * @param mesh defines the source mesh
  93972. * @param name defines the name to use for the new target
  93973. * @param influence defines the influence to attach to the target
  93974. * @returns a new MorphTarget
  93975. */
  93976. MorphTarget.FromMesh = function (mesh, name, influence) {
  93977. if (!name) {
  93978. name = mesh.name;
  93979. }
  93980. var result = new MorphTarget(name, influence, mesh.getScene());
  93981. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  93982. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  93983. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  93984. }
  93985. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  93986. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  93987. }
  93988. return result;
  93989. };
  93990. return MorphTarget;
  93991. }());
  93992. BABYLON.MorphTarget = MorphTarget;
  93993. })(BABYLON || (BABYLON = {}));
  93994. //# sourceMappingURL=babylon.morphTarget.js.map
  93995. var BABYLON;
  93996. (function (BABYLON) {
  93997. /**
  93998. * This class is used to deform meshes using morphing between different targets
  93999. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  94000. */
  94001. var MorphTargetManager = /** @class */ (function () {
  94002. /**
  94003. * Creates a new MorphTargetManager
  94004. * @param scene defines the current scene
  94005. */
  94006. function MorphTargetManager(scene) {
  94007. if (scene === void 0) { scene = null; }
  94008. this._targets = new Array();
  94009. this._targetObservable = new Array();
  94010. this._activeTargets = new BABYLON.SmartArray(16);
  94011. this._supportsNormals = false;
  94012. this._supportsTangents = false;
  94013. this._vertexCount = 0;
  94014. this._uniqueId = 0;
  94015. this._tempInfluences = new Array();
  94016. if (!scene) {
  94017. scene = BABYLON.Engine.LastCreatedScene;
  94018. }
  94019. this._scene = scene;
  94020. if (this._scene) {
  94021. this._scene.morphTargetManagers.push(this);
  94022. this._uniqueId = this._scene.getUniqueId();
  94023. }
  94024. }
  94025. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  94026. /**
  94027. * Gets the unique ID of this manager
  94028. */
  94029. get: function () {
  94030. return this._uniqueId;
  94031. },
  94032. enumerable: true,
  94033. configurable: true
  94034. });
  94035. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  94036. /**
  94037. * Gets the number of vertices handled by this manager
  94038. */
  94039. get: function () {
  94040. return this._vertexCount;
  94041. },
  94042. enumerable: true,
  94043. configurable: true
  94044. });
  94045. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  94046. /**
  94047. * Gets a boolean indicating if this manager supports morphing of normals
  94048. */
  94049. get: function () {
  94050. return this._supportsNormals;
  94051. },
  94052. enumerable: true,
  94053. configurable: true
  94054. });
  94055. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  94056. /**
  94057. * Gets a boolean indicating if this manager supports morphing of tangents
  94058. */
  94059. get: function () {
  94060. return this._supportsTangents;
  94061. },
  94062. enumerable: true,
  94063. configurable: true
  94064. });
  94065. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  94066. /**
  94067. * Gets the number of targets stored in this manager
  94068. */
  94069. get: function () {
  94070. return this._targets.length;
  94071. },
  94072. enumerable: true,
  94073. configurable: true
  94074. });
  94075. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  94076. /**
  94077. * Gets the number of influencers (ie. the number of targets with influences > 0)
  94078. */
  94079. get: function () {
  94080. return this._activeTargets.length;
  94081. },
  94082. enumerable: true,
  94083. configurable: true
  94084. });
  94085. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  94086. /**
  94087. * Gets the list of influences (one per target)
  94088. */
  94089. get: function () {
  94090. return this._influences;
  94091. },
  94092. enumerable: true,
  94093. configurable: true
  94094. });
  94095. /**
  94096. * Gets the active target at specified index. An active target is a target with an influence > 0
  94097. * @param index defines the index to check
  94098. * @returns the requested target
  94099. */
  94100. MorphTargetManager.prototype.getActiveTarget = function (index) {
  94101. return this._activeTargets.data[index];
  94102. };
  94103. /**
  94104. * Gets the target at specified index
  94105. * @param index defines the index to check
  94106. * @returns the requested target
  94107. */
  94108. MorphTargetManager.prototype.getTarget = function (index) {
  94109. return this._targets[index];
  94110. };
  94111. /**
  94112. * Add a new target to this manager
  94113. * @param target defines the target to add
  94114. */
  94115. MorphTargetManager.prototype.addTarget = function (target) {
  94116. var _this = this;
  94117. this._targets.push(target);
  94118. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  94119. _this._syncActiveTargets(needUpdate);
  94120. }));
  94121. this._syncActiveTargets(true);
  94122. };
  94123. /**
  94124. * Removes a target from the manager
  94125. * @param target defines the target to remove
  94126. */
  94127. MorphTargetManager.prototype.removeTarget = function (target) {
  94128. var index = this._targets.indexOf(target);
  94129. if (index >= 0) {
  94130. this._targets.splice(index, 1);
  94131. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  94132. this._syncActiveTargets(true);
  94133. }
  94134. };
  94135. /**
  94136. * Serializes the current manager into a Serialization object
  94137. * @returns the serialized object
  94138. */
  94139. MorphTargetManager.prototype.serialize = function () {
  94140. var serializationObject = {};
  94141. serializationObject.id = this.uniqueId;
  94142. serializationObject.targets = [];
  94143. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  94144. var target = _a[_i];
  94145. serializationObject.targets.push(target.serialize());
  94146. }
  94147. return serializationObject;
  94148. };
  94149. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  94150. var influenceCount = 0;
  94151. this._activeTargets.reset();
  94152. this._supportsNormals = true;
  94153. this._supportsTangents = true;
  94154. this._vertexCount = 0;
  94155. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  94156. var target = _a[_i];
  94157. this._activeTargets.push(target);
  94158. this._tempInfluences[influenceCount++] = target.influence;
  94159. var positions = target.getPositions();
  94160. if (positions) {
  94161. this._supportsNormals = this._supportsNormals && target.hasNormals;
  94162. this._supportsTangents = this._supportsTangents && target.hasTangents;
  94163. var vertexCount = positions.length / 3;
  94164. if (this._vertexCount === 0) {
  94165. this._vertexCount = vertexCount;
  94166. }
  94167. else if (this._vertexCount !== vertexCount) {
  94168. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  94169. return;
  94170. }
  94171. }
  94172. }
  94173. if (!this._influences || this._influences.length !== influenceCount) {
  94174. this._influences = new Float32Array(influenceCount);
  94175. }
  94176. for (var index = 0; index < influenceCount; index++) {
  94177. this._influences[index] = this._tempInfluences[index];
  94178. }
  94179. if (needUpdate) {
  94180. this.synchronize();
  94181. }
  94182. };
  94183. /**
  94184. * Syncrhonize the targets with all the meshes using this morph target manager
  94185. */
  94186. MorphTargetManager.prototype.synchronize = function () {
  94187. if (!this._scene) {
  94188. return;
  94189. }
  94190. // Flag meshes as dirty to resync with the active targets
  94191. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  94192. var mesh = _a[_i];
  94193. if (mesh.morphTargetManager === this) {
  94194. mesh._syncGeometryWithMorphTargetManager();
  94195. }
  94196. }
  94197. };
  94198. // Statics
  94199. /**
  94200. * Creates a new MorphTargetManager from serialized data
  94201. * @param serializationObject defines the serialized data
  94202. * @param scene defines the hosting scene
  94203. * @returns the new MorphTargetManager
  94204. */
  94205. MorphTargetManager.Parse = function (serializationObject, scene) {
  94206. var result = new MorphTargetManager(scene);
  94207. result._uniqueId = serializationObject.id;
  94208. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  94209. var targetData = _a[_i];
  94210. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  94211. }
  94212. return result;
  94213. };
  94214. return MorphTargetManager;
  94215. }());
  94216. BABYLON.MorphTargetManager = MorphTargetManager;
  94217. })(BABYLON || (BABYLON = {}));
  94218. //# sourceMappingURL=babylon.morphTargetManager.js.map
  94219. var BABYLON;
  94220. (function (BABYLON) {
  94221. var Octree = /** @class */ (function () {
  94222. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  94223. if (maxDepth === void 0) { maxDepth = 2; }
  94224. this.maxDepth = maxDepth;
  94225. this.dynamicContent = new Array();
  94226. this._maxBlockCapacity = maxBlockCapacity || 64;
  94227. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  94228. this._creationFunc = creationFunc;
  94229. }
  94230. // Methods
  94231. Octree.prototype.update = function (worldMin, worldMax, entries) {
  94232. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  94233. };
  94234. Octree.prototype.addMesh = function (entry) {
  94235. for (var index = 0; index < this.blocks.length; index++) {
  94236. var block = this.blocks[index];
  94237. block.addEntry(entry);
  94238. }
  94239. };
  94240. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  94241. this._selectionContent.reset();
  94242. for (var index = 0; index < this.blocks.length; index++) {
  94243. var block = this.blocks[index];
  94244. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  94245. }
  94246. if (allowDuplicate) {
  94247. this._selectionContent.concat(this.dynamicContent);
  94248. }
  94249. else {
  94250. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  94251. }
  94252. return this._selectionContent;
  94253. };
  94254. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  94255. this._selectionContent.reset();
  94256. for (var index = 0; index < this.blocks.length; index++) {
  94257. var block = this.blocks[index];
  94258. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  94259. }
  94260. if (allowDuplicate) {
  94261. this._selectionContent.concat(this.dynamicContent);
  94262. }
  94263. else {
  94264. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  94265. }
  94266. return this._selectionContent;
  94267. };
  94268. Octree.prototype.intersectsRay = function (ray) {
  94269. this._selectionContent.reset();
  94270. for (var index = 0; index < this.blocks.length; index++) {
  94271. var block = this.blocks[index];
  94272. block.intersectsRay(ray, this._selectionContent);
  94273. }
  94274. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  94275. return this._selectionContent;
  94276. };
  94277. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  94278. target.blocks = new Array();
  94279. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  94280. // Segmenting space
  94281. for (var x = 0; x < 2; x++) {
  94282. for (var y = 0; y < 2; y++) {
  94283. for (var z = 0; z < 2; z++) {
  94284. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  94285. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  94286. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  94287. block.addEntries(entries);
  94288. target.blocks.push(block);
  94289. }
  94290. }
  94291. }
  94292. };
  94293. Octree.CreationFuncForMeshes = function (entry, block) {
  94294. var boundingInfo = entry.getBoundingInfo();
  94295. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  94296. block.entries.push(entry);
  94297. }
  94298. };
  94299. Octree.CreationFuncForSubMeshes = function (entry, block) {
  94300. var boundingInfo = entry.getBoundingInfo();
  94301. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  94302. block.entries.push(entry);
  94303. }
  94304. };
  94305. return Octree;
  94306. }());
  94307. BABYLON.Octree = Octree;
  94308. })(BABYLON || (BABYLON = {}));
  94309. //# sourceMappingURL=babylon.octree.js.map
  94310. var BABYLON;
  94311. (function (BABYLON) {
  94312. var OctreeBlock = /** @class */ (function () {
  94313. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  94314. this.entries = new Array();
  94315. this._boundingVectors = new Array();
  94316. this._capacity = capacity;
  94317. this._depth = depth;
  94318. this._maxDepth = maxDepth;
  94319. this._creationFunc = creationFunc;
  94320. this._minPoint = minPoint;
  94321. this._maxPoint = maxPoint;
  94322. this._boundingVectors.push(minPoint.clone());
  94323. this._boundingVectors.push(maxPoint.clone());
  94324. this._boundingVectors.push(minPoint.clone());
  94325. this._boundingVectors[2].x = maxPoint.x;
  94326. this._boundingVectors.push(minPoint.clone());
  94327. this._boundingVectors[3].y = maxPoint.y;
  94328. this._boundingVectors.push(minPoint.clone());
  94329. this._boundingVectors[4].z = maxPoint.z;
  94330. this._boundingVectors.push(maxPoint.clone());
  94331. this._boundingVectors[5].z = minPoint.z;
  94332. this._boundingVectors.push(maxPoint.clone());
  94333. this._boundingVectors[6].x = minPoint.x;
  94334. this._boundingVectors.push(maxPoint.clone());
  94335. this._boundingVectors[7].y = minPoint.y;
  94336. }
  94337. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  94338. // Property
  94339. get: function () {
  94340. return this._capacity;
  94341. },
  94342. enumerable: true,
  94343. configurable: true
  94344. });
  94345. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  94346. get: function () {
  94347. return this._minPoint;
  94348. },
  94349. enumerable: true,
  94350. configurable: true
  94351. });
  94352. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  94353. get: function () {
  94354. return this._maxPoint;
  94355. },
  94356. enumerable: true,
  94357. configurable: true
  94358. });
  94359. // Methods
  94360. OctreeBlock.prototype.addEntry = function (entry) {
  94361. if (this.blocks) {
  94362. for (var index = 0; index < this.blocks.length; index++) {
  94363. var block = this.blocks[index];
  94364. block.addEntry(entry);
  94365. }
  94366. return;
  94367. }
  94368. this._creationFunc(entry, this);
  94369. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  94370. this.createInnerBlocks();
  94371. }
  94372. };
  94373. OctreeBlock.prototype.addEntries = function (entries) {
  94374. for (var index = 0; index < entries.length; index++) {
  94375. var mesh = entries[index];
  94376. this.addEntry(mesh);
  94377. }
  94378. };
  94379. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  94380. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  94381. if (this.blocks) {
  94382. for (var index = 0; index < this.blocks.length; index++) {
  94383. var block = this.blocks[index];
  94384. block.select(frustumPlanes, selection, allowDuplicate);
  94385. }
  94386. return;
  94387. }
  94388. if (allowDuplicate) {
  94389. selection.concat(this.entries);
  94390. }
  94391. else {
  94392. selection.concatWithNoDuplicate(this.entries);
  94393. }
  94394. }
  94395. };
  94396. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  94397. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  94398. if (this.blocks) {
  94399. for (var index = 0; index < this.blocks.length; index++) {
  94400. var block = this.blocks[index];
  94401. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  94402. }
  94403. return;
  94404. }
  94405. if (allowDuplicate) {
  94406. selection.concat(this.entries);
  94407. }
  94408. else {
  94409. selection.concatWithNoDuplicate(this.entries);
  94410. }
  94411. }
  94412. };
  94413. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  94414. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  94415. if (this.blocks) {
  94416. for (var index = 0; index < this.blocks.length; index++) {
  94417. var block = this.blocks[index];
  94418. block.intersectsRay(ray, selection);
  94419. }
  94420. return;
  94421. }
  94422. selection.concatWithNoDuplicate(this.entries);
  94423. }
  94424. };
  94425. OctreeBlock.prototype.createInnerBlocks = function () {
  94426. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  94427. };
  94428. return OctreeBlock;
  94429. }());
  94430. BABYLON.OctreeBlock = OctreeBlock;
  94431. })(BABYLON || (BABYLON = {}));
  94432. //# sourceMappingURL=babylon.octreeBlock.js.map
  94433. var BABYLON;
  94434. (function (BABYLON) {
  94435. /**
  94436. * Postprocess used to generate anaglyphic rendering
  94437. */
  94438. var AnaglyphPostProcess = /** @class */ (function (_super) {
  94439. __extends(AnaglyphPostProcess, _super);
  94440. /**
  94441. * Creates a new AnaglyphPostProcess
  94442. * @param name defines postprocess name
  94443. * @param options defines creation options or target ratio scale
  94444. * @param rigCameras defines cameras using this postprocess
  94445. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  94446. * @param engine defines hosting engine
  94447. * @param reusable defines if the postprocess will be reused multiple times per frame
  94448. */
  94449. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  94450. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  94451. _this._passedProcess = rigCameras[0]._rigPostProcess;
  94452. _this.onApplyObservable.add(function (effect) {
  94453. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  94454. });
  94455. return _this;
  94456. }
  94457. return AnaglyphPostProcess;
  94458. }(BABYLON.PostProcess));
  94459. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  94460. })(BABYLON || (BABYLON = {}));
  94461. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  94462. var BABYLON;
  94463. (function (BABYLON) {
  94464. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  94465. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  94466. });
  94467. /**
  94468. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  94469. */
  94470. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  94471. __extends(AnaglyphArcRotateCamera, _super);
  94472. /**
  94473. * Creates a new AnaglyphArcRotateCamera
  94474. * @param name defines camera name
  94475. * @param alpha defines alpha angle (in radians)
  94476. * @param beta defines beta angle (in radians)
  94477. * @param radius defines radius
  94478. * @param target defines camera target
  94479. * @param interaxialDistance defines distance between each color axis
  94480. * @param scene defines the hosting scene
  94481. */
  94482. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  94483. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  94484. _this.interaxialDistance = interaxialDistance;
  94485. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  94486. return _this;
  94487. }
  94488. /**
  94489. * Gets camera class name
  94490. * @returns AnaglyphArcRotateCamera
  94491. */
  94492. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  94493. return "AnaglyphArcRotateCamera";
  94494. };
  94495. return AnaglyphArcRotateCamera;
  94496. }(BABYLON.ArcRotateCamera));
  94497. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  94498. })(BABYLON || (BABYLON = {}));
  94499. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  94500. var BABYLON;
  94501. (function (BABYLON) {
  94502. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  94503. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  94504. });
  94505. /**
  94506. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  94507. */
  94508. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  94509. __extends(AnaglyphFreeCamera, _super);
  94510. /**
  94511. * Creates a new AnaglyphFreeCamera
  94512. * @param name defines camera name
  94513. * @param position defines initial position
  94514. * @param interaxialDistance defines distance between each color axis
  94515. * @param scene defines the hosting scene
  94516. */
  94517. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  94518. var _this = _super.call(this, name, position, scene) || this;
  94519. _this.interaxialDistance = interaxialDistance;
  94520. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  94521. return _this;
  94522. }
  94523. /**
  94524. * Gets camera class name
  94525. * @returns AnaglyphFreeCamera
  94526. */
  94527. AnaglyphFreeCamera.prototype.getClassName = function () {
  94528. return "AnaglyphFreeCamera";
  94529. };
  94530. return AnaglyphFreeCamera;
  94531. }(BABYLON.FreeCamera));
  94532. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  94533. })(BABYLON || (BABYLON = {}));
  94534. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  94535. var BABYLON;
  94536. (function (BABYLON) {
  94537. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  94538. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  94539. });
  94540. /**
  94541. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  94542. */
  94543. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  94544. __extends(AnaglyphGamepadCamera, _super);
  94545. /**
  94546. * Creates a new AnaglyphGamepadCamera
  94547. * @param name defines camera name
  94548. * @param position defines initial position
  94549. * @param interaxialDistance defines distance between each color axis
  94550. * @param scene defines the hosting scene
  94551. */
  94552. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  94553. var _this = _super.call(this, name, position, scene) || this;
  94554. _this.interaxialDistance = interaxialDistance;
  94555. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  94556. return _this;
  94557. }
  94558. /**
  94559. * Gets camera class name
  94560. * @returns AnaglyphGamepadCamera
  94561. */
  94562. AnaglyphGamepadCamera.prototype.getClassName = function () {
  94563. return "AnaglyphGamepadCamera";
  94564. };
  94565. return AnaglyphGamepadCamera;
  94566. }(BABYLON.GamepadCamera));
  94567. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  94568. })(BABYLON || (BABYLON = {}));
  94569. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  94570. var BABYLON;
  94571. (function (BABYLON) {
  94572. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  94573. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  94574. });
  94575. /**
  94576. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  94577. */
  94578. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  94579. __extends(AnaglyphUniversalCamera, _super);
  94580. /**
  94581. * Creates a new AnaglyphUniversalCamera
  94582. * @param name defines camera name
  94583. * @param position defines initial position
  94584. * @param interaxialDistance defines distance between each color axis
  94585. * @param scene defines the hosting scene
  94586. */
  94587. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  94588. var _this = _super.call(this, name, position, scene) || this;
  94589. _this.interaxialDistance = interaxialDistance;
  94590. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  94591. return _this;
  94592. }
  94593. /**
  94594. * Gets camera class name
  94595. * @returns AnaglyphUniversalCamera
  94596. */
  94597. AnaglyphUniversalCamera.prototype.getClassName = function () {
  94598. return "AnaglyphUniversalCamera";
  94599. };
  94600. return AnaglyphUniversalCamera;
  94601. }(BABYLON.UniversalCamera));
  94602. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  94603. })(BABYLON || (BABYLON = {}));
  94604. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  94605. var BABYLON;
  94606. (function (BABYLON) {
  94607. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  94608. __extends(StereoscopicInterlacePostProcess, _super);
  94609. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  94610. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  94611. _this._passedProcess = rigCameras[0]._rigPostProcess;
  94612. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  94613. _this.onSizeChangedObservable.add(function () {
  94614. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  94615. });
  94616. _this.onApplyObservable.add(function (effect) {
  94617. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  94618. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  94619. });
  94620. return _this;
  94621. }
  94622. return StereoscopicInterlacePostProcess;
  94623. }(BABYLON.PostProcess));
  94624. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  94625. })(BABYLON || (BABYLON = {}));
  94626. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  94627. var BABYLON;
  94628. (function (BABYLON) {
  94629. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  94630. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  94631. });
  94632. /**
  94633. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  94634. */
  94635. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  94636. __extends(StereoscopicArcRotateCamera, _super);
  94637. /**
  94638. * Creates a new StereoscopicArcRotateCamera
  94639. * @param name defines camera name
  94640. * @param alpha defines alpha angle (in radians)
  94641. * @param beta defines beta angle (in radians)
  94642. * @param radius defines radius
  94643. * @param target defines camera target
  94644. * @param interaxialDistance defines distance between each color axis
  94645. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  94646. * @param scene defines the hosting scene
  94647. */
  94648. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  94649. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  94650. _this.interaxialDistance = interaxialDistance;
  94651. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  94652. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  94653. return _this;
  94654. }
  94655. /**
  94656. * Gets camera class name
  94657. * @returns StereoscopicArcRotateCamera
  94658. */
  94659. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  94660. return "StereoscopicArcRotateCamera";
  94661. };
  94662. return StereoscopicArcRotateCamera;
  94663. }(BABYLON.ArcRotateCamera));
  94664. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  94665. })(BABYLON || (BABYLON = {}));
  94666. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  94667. var BABYLON;
  94668. (function (BABYLON) {
  94669. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  94670. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  94671. });
  94672. /**
  94673. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  94674. */
  94675. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  94676. __extends(StereoscopicFreeCamera, _super);
  94677. /**
  94678. * Creates a new StereoscopicFreeCamera
  94679. * @param name defines camera name
  94680. * @param position defines initial position
  94681. * @param interaxialDistance defines distance between each color axis
  94682. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  94683. * @param scene defines the hosting scene
  94684. */
  94685. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  94686. var _this = _super.call(this, name, position, scene) || this;
  94687. _this.interaxialDistance = interaxialDistance;
  94688. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  94689. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  94690. return _this;
  94691. }
  94692. /**
  94693. * Gets camera class name
  94694. * @returns StereoscopicFreeCamera
  94695. */
  94696. StereoscopicFreeCamera.prototype.getClassName = function () {
  94697. return "StereoscopicFreeCamera";
  94698. };
  94699. return StereoscopicFreeCamera;
  94700. }(BABYLON.FreeCamera));
  94701. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  94702. })(BABYLON || (BABYLON = {}));
  94703. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  94704. var BABYLON;
  94705. (function (BABYLON) {
  94706. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  94707. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  94708. });
  94709. /**
  94710. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  94711. */
  94712. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  94713. __extends(StereoscopicGamepadCamera, _super);
  94714. /**
  94715. * Creates a new StereoscopicGamepadCamera
  94716. * @param name defines camera name
  94717. * @param position defines initial position
  94718. * @param interaxialDistance defines distance between each color axis
  94719. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  94720. * @param scene defines the hosting scene
  94721. */
  94722. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  94723. var _this = _super.call(this, name, position, scene) || this;
  94724. _this.interaxialDistance = interaxialDistance;
  94725. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  94726. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  94727. return _this;
  94728. }
  94729. /**
  94730. * Gets camera class name
  94731. * @returns StereoscopicGamepadCamera
  94732. */
  94733. StereoscopicGamepadCamera.prototype.getClassName = function () {
  94734. return "StereoscopicGamepadCamera";
  94735. };
  94736. return StereoscopicGamepadCamera;
  94737. }(BABYLON.GamepadCamera));
  94738. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  94739. })(BABYLON || (BABYLON = {}));
  94740. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  94741. var BABYLON;
  94742. (function (BABYLON) {
  94743. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  94744. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  94745. });
  94746. /**
  94747. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  94748. */
  94749. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  94750. __extends(StereoscopicUniversalCamera, _super);
  94751. /**
  94752. * Creates a new StereoscopicUniversalCamera
  94753. * @param name defines camera name
  94754. * @param position defines initial position
  94755. * @param interaxialDistance defines distance between each color axis
  94756. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  94757. * @param scene defines the hosting scene
  94758. */
  94759. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  94760. var _this = _super.call(this, name, position, scene) || this;
  94761. _this.interaxialDistance = interaxialDistance;
  94762. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  94763. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  94764. return _this;
  94765. }
  94766. /**
  94767. * Gets camera class name
  94768. * @returns StereoscopicUniversalCamera
  94769. */
  94770. StereoscopicUniversalCamera.prototype.getClassName = function () {
  94771. return "StereoscopicUniversalCamera";
  94772. };
  94773. return StereoscopicUniversalCamera;
  94774. }(BABYLON.UniversalCamera));
  94775. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  94776. })(BABYLON || (BABYLON = {}));
  94777. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  94778. var BABYLON;
  94779. (function (BABYLON) {
  94780. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  94781. __extends(VRDistortionCorrectionPostProcess, _super);
  94782. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  94783. var _this = _super.call(this, name, "vrDistortionCorrection", [
  94784. 'LensCenter',
  94785. 'Scale',
  94786. 'ScaleIn',
  94787. 'HmdWarpParam'
  94788. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  94789. _this._isRightEye = isRightEye;
  94790. _this._distortionFactors = vrMetrics.distortionK;
  94791. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  94792. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  94793. _this.adaptScaleToCurrentViewport = true;
  94794. _this.onSizeChangedObservable.add(function () {
  94795. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  94796. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  94797. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  94798. });
  94799. _this.onApplyObservable.add(function (effect) {
  94800. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  94801. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  94802. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  94803. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  94804. });
  94805. return _this;
  94806. }
  94807. return VRDistortionCorrectionPostProcess;
  94808. }(BABYLON.PostProcess));
  94809. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  94810. })(BABYLON || (BABYLON = {}));
  94811. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  94812. var BABYLON;
  94813. (function (BABYLON) {
  94814. /**
  94815. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  94816. * Screen rotation is taken into account.
  94817. */
  94818. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  94819. function FreeCameraDeviceOrientationInput() {
  94820. var _this = this;
  94821. this._screenOrientationAngle = 0;
  94822. this._screenQuaternion = new BABYLON.Quaternion();
  94823. this._alpha = 0;
  94824. this._beta = 0;
  94825. this._gamma = 0;
  94826. this._orientationChanged = function () {
  94827. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  94828. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  94829. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  94830. };
  94831. this._deviceOrientation = function (evt) {
  94832. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  94833. _this._beta = evt.beta !== null ? evt.beta : 0;
  94834. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  94835. };
  94836. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  94837. this._orientationChanged();
  94838. }
  94839. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  94840. get: function () {
  94841. return this._camera;
  94842. },
  94843. set: function (camera) {
  94844. this._camera = camera;
  94845. if (this._camera != null && !this._camera.rotationQuaternion) {
  94846. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  94847. }
  94848. },
  94849. enumerable: true,
  94850. configurable: true
  94851. });
  94852. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  94853. window.addEventListener("orientationchange", this._orientationChanged);
  94854. window.addEventListener("deviceorientation", this._deviceOrientation);
  94855. //In certain cases, the attach control is called AFTER orientation was changed,
  94856. //So this is needed.
  94857. this._orientationChanged();
  94858. };
  94859. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  94860. window.removeEventListener("orientationchange", this._orientationChanged);
  94861. window.removeEventListener("deviceorientation", this._deviceOrientation);
  94862. };
  94863. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  94864. //if no device orientation provided, don't update the rotation.
  94865. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  94866. if (!this._alpha)
  94867. return;
  94868. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  94869. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  94870. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  94871. //Mirror on XY Plane
  94872. this._camera.rotationQuaternion.z *= -1;
  94873. this._camera.rotationQuaternion.w *= -1;
  94874. };
  94875. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  94876. return "FreeCameraDeviceOrientationInput";
  94877. };
  94878. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  94879. return "deviceOrientation";
  94880. };
  94881. return FreeCameraDeviceOrientationInput;
  94882. }());
  94883. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  94884. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  94885. })(BABYLON || (BABYLON = {}));
  94886. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  94887. var BABYLON;
  94888. (function (BABYLON) {
  94889. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  94890. function ArcRotateCameraVRDeviceOrientationInput() {
  94891. this.alphaCorrection = 1;
  94892. this.betaCorrection = 1;
  94893. this.gammaCorrection = 1;
  94894. this._alpha = 0;
  94895. this._gamma = 0;
  94896. this._dirty = false;
  94897. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  94898. }
  94899. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  94900. this.camera.attachControl(element, noPreventDefault);
  94901. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  94902. };
  94903. /** @hidden */
  94904. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  94905. if (evt.alpha !== null) {
  94906. this._alpha = +evt.alpha | 0;
  94907. }
  94908. if (evt.gamma !== null) {
  94909. this._gamma = +evt.gamma | 0;
  94910. }
  94911. this._dirty = true;
  94912. };
  94913. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  94914. if (this._dirty) {
  94915. this._dirty = false;
  94916. if (this._gamma < 0) {
  94917. this._gamma = 180 + this._gamma;
  94918. }
  94919. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  94920. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  94921. }
  94922. };
  94923. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  94924. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  94925. };
  94926. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  94927. return "ArcRotateCameraVRDeviceOrientationInput";
  94928. };
  94929. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  94930. return "VRDeviceOrientation";
  94931. };
  94932. return ArcRotateCameraVRDeviceOrientationInput;
  94933. }());
  94934. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  94935. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  94936. })(BABYLON || (BABYLON = {}));
  94937. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  94938. var BABYLON;
  94939. (function (BABYLON) {
  94940. var VRCameraMetrics = /** @class */ (function () {
  94941. function VRCameraMetrics() {
  94942. this.compensateDistortion = true;
  94943. }
  94944. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  94945. get: function () {
  94946. return this.hResolution / (2 * this.vResolution);
  94947. },
  94948. enumerable: true,
  94949. configurable: true
  94950. });
  94951. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  94952. get: function () {
  94953. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  94954. },
  94955. enumerable: true,
  94956. configurable: true
  94957. });
  94958. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  94959. get: function () {
  94960. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  94961. var h = (4 * meters) / this.hScreenSize;
  94962. return BABYLON.Matrix.Translation(h, 0, 0);
  94963. },
  94964. enumerable: true,
  94965. configurable: true
  94966. });
  94967. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  94968. get: function () {
  94969. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  94970. var h = (4 * meters) / this.hScreenSize;
  94971. return BABYLON.Matrix.Translation(-h, 0, 0);
  94972. },
  94973. enumerable: true,
  94974. configurable: true
  94975. });
  94976. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  94977. get: function () {
  94978. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  94979. },
  94980. enumerable: true,
  94981. configurable: true
  94982. });
  94983. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  94984. get: function () {
  94985. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  94986. },
  94987. enumerable: true,
  94988. configurable: true
  94989. });
  94990. VRCameraMetrics.GetDefault = function () {
  94991. var result = new VRCameraMetrics();
  94992. result.hResolution = 1280;
  94993. result.vResolution = 800;
  94994. result.hScreenSize = 0.149759993;
  94995. result.vScreenSize = 0.0935999975;
  94996. result.vScreenCenter = 0.0467999987;
  94997. result.eyeToScreenDistance = 0.0410000011;
  94998. result.lensSeparationDistance = 0.0635000020;
  94999. result.interpupillaryDistance = 0.0640000030;
  95000. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  95001. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  95002. result.postProcessScaleFactor = 1.714605507808412;
  95003. result.lensCenterOffset = 0.151976421;
  95004. return result;
  95005. };
  95006. return VRCameraMetrics;
  95007. }());
  95008. BABYLON.VRCameraMetrics = VRCameraMetrics;
  95009. })(BABYLON || (BABYLON = {}));
  95010. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  95011. var BABYLON;
  95012. (function (BABYLON) {
  95013. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  95014. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  95015. });
  95016. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  95017. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  95018. });
  95019. /**
  95020. * This represents a WebVR camera.
  95021. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  95022. * @example http://doc.babylonjs.com/how_to/webvr_camera
  95023. */
  95024. var WebVRFreeCamera = /** @class */ (function (_super) {
  95025. __extends(WebVRFreeCamera, _super);
  95026. /**
  95027. * Instantiates a WebVRFreeCamera.
  95028. * @param name The name of the WebVRFreeCamera
  95029. * @param position The starting anchor position for the camera
  95030. * @param scene The scene the camera belongs to
  95031. * @param webVROptions a set of customizable options for the webVRCamera
  95032. */
  95033. function WebVRFreeCamera(name, position, scene, webVROptions) {
  95034. if (webVROptions === void 0) { webVROptions = {}; }
  95035. var _this = _super.call(this, name, position, scene) || this;
  95036. _this.webVROptions = webVROptions;
  95037. /**
  95038. * @hidden
  95039. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  95040. */
  95041. _this._vrDevice = null;
  95042. /**
  95043. * The rawPose of the vrDevice.
  95044. */
  95045. _this.rawPose = null;
  95046. _this._specsVersion = "1.1";
  95047. _this._attached = false;
  95048. _this._descendants = [];
  95049. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  95050. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  95051. /** @hidden */
  95052. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  95053. _this._standingMatrix = null;
  95054. /**
  95055. * Represents device position in babylon space.
  95056. */
  95057. _this.devicePosition = BABYLON.Vector3.Zero();
  95058. /**
  95059. * Represents device rotation in babylon space.
  95060. */
  95061. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  95062. /**
  95063. * The scale of the device to be used when translating from device space to babylon space.
  95064. */
  95065. _this.deviceScaleFactor = 1;
  95066. _this._deviceToWorld = BABYLON.Matrix.Identity();
  95067. _this._worldToDevice = BABYLON.Matrix.Identity();
  95068. /**
  95069. * References to the webVR controllers for the vrDevice.
  95070. */
  95071. _this.controllers = [];
  95072. /**
  95073. * Emits an event when a controller is attached.
  95074. */
  95075. _this.onControllersAttachedObservable = new BABYLON.Observable();
  95076. /**
  95077. * Emits an event when a controller's mesh has been loaded;
  95078. */
  95079. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  95080. /**
  95081. * Emits an event when the HMD's pose has been updated.
  95082. */
  95083. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  95084. _this._poseSet = false;
  95085. /**
  95086. * If the rig cameras be used as parent instead of this camera.
  95087. */
  95088. _this.rigParenting = true;
  95089. _this._defaultHeight = undefined;
  95090. _this._htmlElementAttached = null;
  95091. _this._detachIfAttached = function () {
  95092. var vrDisplay = _this.getEngine().getVRDevice();
  95093. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  95094. _this.detachControl(_this._htmlElementAttached);
  95095. }
  95096. };
  95097. _this._workingVector = BABYLON.Vector3.Zero();
  95098. _this._oneVector = BABYLON.Vector3.One();
  95099. _this._workingMatrix = BABYLON.Matrix.Identity();
  95100. _this._tmpMatrix = new BABYLON.Matrix();
  95101. _this._cache.position = BABYLON.Vector3.Zero();
  95102. if (webVROptions.defaultHeight) {
  95103. _this._defaultHeight = webVROptions.defaultHeight;
  95104. _this.position.y = _this._defaultHeight;
  95105. }
  95106. _this.minZ = 0.1;
  95107. //legacy support - the compensation boolean was removed.
  95108. if (arguments.length === 5) {
  95109. _this.webVROptions = arguments[4];
  95110. }
  95111. // default webVR options
  95112. if (_this.webVROptions.trackPosition == undefined) {
  95113. _this.webVROptions.trackPosition = true;
  95114. }
  95115. if (_this.webVROptions.controllerMeshes == undefined) {
  95116. _this.webVROptions.controllerMeshes = true;
  95117. }
  95118. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  95119. _this.webVROptions.defaultLightingOnControllers = true;
  95120. }
  95121. _this.rotationQuaternion = new BABYLON.Quaternion();
  95122. if (_this.webVROptions && _this.webVROptions.positionScale) {
  95123. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  95124. }
  95125. //enable VR
  95126. var engine = _this.getEngine();
  95127. _this._onVREnabled = function (success) { if (success) {
  95128. _this.initControllers();
  95129. } };
  95130. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  95131. engine.initWebVR().add(function (event) {
  95132. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  95133. return;
  95134. }
  95135. _this._vrDevice = event.vrDisplay;
  95136. //reset the rig parameters.
  95137. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  95138. if (_this._attached) {
  95139. _this.getEngine().enableVR();
  95140. }
  95141. });
  95142. if (typeof (VRFrameData) !== "undefined")
  95143. _this._frameData = new VRFrameData();
  95144. /**
  95145. * The idea behind the following lines:
  95146. * objects that have the camera as parent should actually have the rig cameras as a parent.
  95147. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  95148. * the second will not show it correctly.
  95149. *
  95150. * To solve this - each object that has the camera as parent will be added to a protected array.
  95151. * When the rig camera renders, it will take this array and set all of those to be its children.
  95152. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  95153. * Amazing!
  95154. */
  95155. scene.onBeforeCameraRenderObservable.add(function (camera) {
  95156. if (camera.parent === _this && _this.rigParenting) {
  95157. _this._descendants = _this.getDescendants(true, function (n) {
  95158. // don't take the cameras or the controllers!
  95159. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  95160. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  95161. return !isController && !isRigCamera;
  95162. });
  95163. _this._descendants.forEach(function (node) {
  95164. node.parent = camera;
  95165. });
  95166. }
  95167. });
  95168. scene.onAfterCameraRenderObservable.add(function (camera) {
  95169. if (camera.parent === _this && _this.rigParenting) {
  95170. _this._descendants.forEach(function (node) {
  95171. node.parent = _this;
  95172. });
  95173. }
  95174. });
  95175. return _this;
  95176. }
  95177. /**
  95178. * Gets the device distance from the ground in meters.
  95179. * @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.
  95180. */
  95181. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  95182. if (this._standingMatrix) {
  95183. // Add standing matrix offset to get real offset from ground in room
  95184. this._standingMatrix.getTranslationToRef(this._workingVector);
  95185. return this._deviceRoomPosition.y + this._workingVector.y;
  95186. }
  95187. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  95188. return this._defaultHeight || 0;
  95189. };
  95190. /**
  95191. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  95192. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  95193. */
  95194. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  95195. var _this = this;
  95196. if (callback === void 0) { callback = function (bool) { }; }
  95197. // Use standing matrix if available
  95198. this.getEngine().initWebVRAsync().then(function (result) {
  95199. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  95200. callback(false);
  95201. }
  95202. else {
  95203. _this._standingMatrix = new BABYLON.Matrix();
  95204. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  95205. if (!_this.getScene().useRightHandedSystem) {
  95206. [2, 6, 8, 9, 14].forEach(function (num) {
  95207. if (_this._standingMatrix) {
  95208. _this._standingMatrix.m[num] *= -1;
  95209. }
  95210. });
  95211. }
  95212. callback(true);
  95213. }
  95214. });
  95215. };
  95216. /**
  95217. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  95218. * @returns A promise with a boolean set to if the standing matrix is supported.
  95219. */
  95220. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  95221. var _this = this;
  95222. return new Promise(function (res, rej) {
  95223. _this.useStandingMatrix(function (supported) {
  95224. res(supported);
  95225. });
  95226. });
  95227. };
  95228. /**
  95229. * Disposes the camera
  95230. */
  95231. WebVRFreeCamera.prototype.dispose = function () {
  95232. this._detachIfAttached();
  95233. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  95234. _super.prototype.dispose.call(this);
  95235. };
  95236. /**
  95237. * Gets a vrController by name.
  95238. * @param name The name of the controller to retreive
  95239. * @returns the controller matching the name specified or null if not found
  95240. */
  95241. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  95242. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  95243. var gp = _a[_i];
  95244. if (gp.hand === name) {
  95245. return gp;
  95246. }
  95247. }
  95248. return null;
  95249. };
  95250. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  95251. /**
  95252. * The controller corrisponding to the users left hand.
  95253. */
  95254. get: function () {
  95255. if (!this._leftController) {
  95256. this._leftController = this.getControllerByName("left");
  95257. }
  95258. return this._leftController;
  95259. },
  95260. enumerable: true,
  95261. configurable: true
  95262. });
  95263. ;
  95264. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  95265. /**
  95266. * The controller corrisponding to the users right hand.
  95267. */
  95268. get: function () {
  95269. if (!this._rightController) {
  95270. this._rightController = this.getControllerByName("right");
  95271. }
  95272. return this._rightController;
  95273. },
  95274. enumerable: true,
  95275. configurable: true
  95276. });
  95277. ;
  95278. /**
  95279. * Casts a ray forward from the vrCamera's gaze.
  95280. * @param length Length of the ray (default: 100)
  95281. * @returns the ray corrisponding to the gaze
  95282. */
  95283. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  95284. if (length === void 0) { length = 100; }
  95285. if (this.leftCamera) {
  95286. // Use left eye to avoid computation to compute center on every call
  95287. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  95288. }
  95289. else {
  95290. return _super.prototype.getForwardRay.call(this, length);
  95291. }
  95292. };
  95293. /**
  95294. * @hidden
  95295. * Updates the camera based on device's frame data
  95296. */
  95297. WebVRFreeCamera.prototype._checkInputs = function () {
  95298. if (this._vrDevice && this._vrDevice.isPresenting) {
  95299. this._vrDevice.getFrameData(this._frameData);
  95300. this.updateFromDevice(this._frameData.pose);
  95301. }
  95302. _super.prototype._checkInputs.call(this);
  95303. };
  95304. /**
  95305. * Updates the poseControlled values based on the input device pose.
  95306. * @param poseData Pose coming from the device
  95307. */
  95308. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  95309. if (poseData && poseData.orientation) {
  95310. this.rawPose = poseData;
  95311. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  95312. if (this.getScene().useRightHandedSystem) {
  95313. this._deviceRoomRotationQuaternion.z *= -1;
  95314. this._deviceRoomRotationQuaternion.w *= -1;
  95315. }
  95316. if (this.webVROptions.trackPosition && this.rawPose.position) {
  95317. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  95318. if (this.getScene().useRightHandedSystem) {
  95319. this._deviceRoomPosition.z *= -1;
  95320. }
  95321. }
  95322. this._poseSet = true;
  95323. }
  95324. };
  95325. /**
  95326. * WebVR's attach control will start broadcasting frames to the device.
  95327. * Note that in certain browsers (chrome for example) this function must be called
  95328. * within a user-interaction callback. Example:
  95329. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  95330. *
  95331. * @param element html element to attach the vrDevice to
  95332. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  95333. */
  95334. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  95335. _super.prototype.attachControl.call(this, element, noPreventDefault);
  95336. this._attached = true;
  95337. this._htmlElementAttached = element;
  95338. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  95339. if (this._vrDevice) {
  95340. this.getEngine().enableVR();
  95341. }
  95342. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  95343. };
  95344. /**
  95345. * Detaches the camera from the html element and disables VR
  95346. *
  95347. * @param element html element to detach from
  95348. */
  95349. WebVRFreeCamera.prototype.detachControl = function (element) {
  95350. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  95351. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  95352. _super.prototype.detachControl.call(this, element);
  95353. this._attached = false;
  95354. this.getEngine().disableVR();
  95355. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  95356. };
  95357. /**
  95358. * @returns the name of this class
  95359. */
  95360. WebVRFreeCamera.prototype.getClassName = function () {
  95361. return "WebVRFreeCamera";
  95362. };
  95363. /**
  95364. * Calls resetPose on the vrDisplay
  95365. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  95366. */
  95367. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  95368. //uses the vrDisplay's "resetPose()".
  95369. //pitch and roll won't be affected.
  95370. this._vrDevice.resetPose();
  95371. };
  95372. /**
  95373. * @hidden
  95374. * Updates the rig cameras (left and right eye)
  95375. */
  95376. WebVRFreeCamera.prototype._updateRigCameras = function () {
  95377. var camLeft = this._rigCameras[0];
  95378. var camRight = this._rigCameras[1];
  95379. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  95380. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  95381. camLeft.position.copyFrom(this._deviceRoomPosition);
  95382. camRight.position.copyFrom(this._deviceRoomPosition);
  95383. };
  95384. /**
  95385. * @hidden
  95386. * Updates the cached values of the camera
  95387. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  95388. */
  95389. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  95390. var _this = this;
  95391. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  95392. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  95393. if (!this.updateCacheCalled) {
  95394. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  95395. this.updateCacheCalled = true;
  95396. this.update();
  95397. }
  95398. // Set working vector to the device position in room space rotated by the new rotation
  95399. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  95400. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  95401. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  95402. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  95403. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  95404. // Add translation from anchor position
  95405. this._deviceToWorld.getTranslationToRef(this._workingVector);
  95406. this._workingVector.addInPlace(this.position);
  95407. this._workingVector.subtractInPlace(this._cache.position);
  95408. this._deviceToWorld.setTranslation(this._workingVector);
  95409. // Set an inverted matrix to be used when updating the camera
  95410. this._deviceToWorld.invertToRef(this._worldToDevice);
  95411. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  95412. this.controllers.forEach(function (controller) {
  95413. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  95414. controller.update();
  95415. });
  95416. }
  95417. if (!ignoreParentClass) {
  95418. _super.prototype._updateCache.call(this);
  95419. }
  95420. this.updateCacheCalled = false;
  95421. };
  95422. /**
  95423. * Updates the current device position and rotation in the babylon world
  95424. */
  95425. WebVRFreeCamera.prototype.update = function () {
  95426. // Get current device position in babylon world
  95427. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  95428. // Get current device rotation in babylon world
  95429. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  95430. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  95431. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  95432. if (this._poseSet) {
  95433. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  95434. }
  95435. _super.prototype.update.call(this);
  95436. };
  95437. /**
  95438. * @hidden
  95439. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  95440. * @returns an identity matrix
  95441. */
  95442. WebVRFreeCamera.prototype._getViewMatrix = function () {
  95443. return BABYLON.Matrix.Identity();
  95444. };
  95445. /**
  95446. * This function is called by the two RIG cameras.
  95447. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  95448. */
  95449. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  95450. var _this = this;
  95451. // Update the parent camera prior to using a child camera to avoid desynchronization
  95452. var parentCamera = this._cameraRigParams["parentCamera"];
  95453. parentCamera._updateCache();
  95454. //WebVR 1.1
  95455. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  95456. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  95457. if (!this.getScene().useRightHandedSystem) {
  95458. [2, 6, 8, 9, 14].forEach(function (num) {
  95459. _this._webvrViewMatrix.m[num] *= -1;
  95460. });
  95461. }
  95462. // update the camera rotation matrix
  95463. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  95464. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  95465. // Computing target and final matrix
  95466. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  95467. // should the view matrix be updated with scale and position offset?
  95468. if (parentCamera.deviceScaleFactor !== 1) {
  95469. this._webvrViewMatrix.invert();
  95470. // scale the position, if set
  95471. if (parentCamera.deviceScaleFactor) {
  95472. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  95473. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  95474. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  95475. }
  95476. this._webvrViewMatrix.invert();
  95477. }
  95478. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  95479. // Remove translation from 6dof headset if trackposition is set to false
  95480. if (parentCamera.rawPose && parentCamera.rawPose.position && !parentCamera.webVROptions.trackPosition) {
  95481. BABYLON.Matrix.TranslationToRef(parentCamera.rawPose.position[0], parentCamera.rawPose.position[1], -parentCamera.rawPose.position[2], parentCamera._tmpMatrix);
  95482. parentCamera._tmpMatrix.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  95483. }
  95484. // Compute global position
  95485. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  95486. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  95487. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  95488. this._workingMatrix.getTranslationToRef(this._globalPosition);
  95489. this._markSyncedWithParent();
  95490. return this._webvrViewMatrix;
  95491. };
  95492. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  95493. var _this = this;
  95494. var parentCamera = this.parent;
  95495. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  95496. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  95497. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  95498. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  95499. //babylon compatible matrix
  95500. if (!this.getScene().useRightHandedSystem) {
  95501. [8, 9, 10, 11].forEach(function (num) {
  95502. _this._projectionMatrix.m[num] *= -1;
  95503. });
  95504. }
  95505. return this._projectionMatrix;
  95506. };
  95507. /**
  95508. * Initializes the controllers and their meshes
  95509. */
  95510. WebVRFreeCamera.prototype.initControllers = function () {
  95511. var _this = this;
  95512. this.controllers = [];
  95513. var manager = this.getScene().gamepadManager;
  95514. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  95515. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  95516. var webVrController = gamepad;
  95517. if (webVrController.defaultModel) {
  95518. webVrController.defaultModel.setEnabled(false);
  95519. }
  95520. if (webVrController.hand === "right") {
  95521. _this._rightController = null;
  95522. }
  95523. if (webVrController.hand === "left") {
  95524. _this._leftController = null;
  95525. }
  95526. var controllerIndex = _this.controllers.indexOf(webVrController);
  95527. if (controllerIndex !== -1) {
  95528. _this.controllers.splice(controllerIndex, 1);
  95529. }
  95530. }
  95531. });
  95532. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  95533. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  95534. var webVrController_1 = gamepad;
  95535. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  95536. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  95537. if (_this.webVROptions.controllerMeshes) {
  95538. if (webVrController_1.defaultModel) {
  95539. webVrController_1.defaultModel.setEnabled(true);
  95540. }
  95541. else {
  95542. // Load the meshes
  95543. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  95544. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  95545. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  95546. if (_this.webVROptions.defaultLightingOnControllers) {
  95547. if (!_this._lightOnControllers) {
  95548. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  95549. }
  95550. var activateLightOnSubMeshes_1 = function (mesh, light) {
  95551. var children = mesh.getChildren();
  95552. if (children.length !== 0) {
  95553. children.forEach(function (mesh) {
  95554. light.includedOnlyMeshes.push(mesh);
  95555. activateLightOnSubMeshes_1(mesh, light);
  95556. });
  95557. }
  95558. };
  95559. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  95560. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  95561. }
  95562. });
  95563. }
  95564. }
  95565. webVrController_1.attachToPoseControlledCamera(_this);
  95566. // since this is async - sanity check. Is the controller already stored?
  95567. if (_this.controllers.indexOf(webVrController_1) === -1) {
  95568. //add to the controllers array
  95569. _this.controllers.push(webVrController_1);
  95570. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  95571. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  95572. // So we're overriding setting left & right manually to be sure
  95573. var firstViveWandDetected = false;
  95574. for (var i = 0; i < _this.controllers.length; i++) {
  95575. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  95576. if (!firstViveWandDetected) {
  95577. firstViveWandDetected = true;
  95578. _this.controllers[i].hand = "left";
  95579. }
  95580. else {
  95581. _this.controllers[i].hand = "right";
  95582. }
  95583. }
  95584. }
  95585. //did we find enough controllers? Great! let the developer know.
  95586. if (_this.controllers.length >= 2) {
  95587. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  95588. }
  95589. }
  95590. }
  95591. });
  95592. };
  95593. return WebVRFreeCamera;
  95594. }(BABYLON.FreeCamera));
  95595. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  95596. })(BABYLON || (BABYLON = {}));
  95597. //# sourceMappingURL=babylon.webVRCamera.js.map
  95598. var BABYLON;
  95599. (function (BABYLON) {
  95600. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  95601. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  95602. });
  95603. // We're mainly based on the logic defined into the FreeCamera code
  95604. /**
  95605. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  95606. * being tilted forward or back and left or right.
  95607. */
  95608. var DeviceOrientationCamera = /** @class */ (function (_super) {
  95609. __extends(DeviceOrientationCamera, _super);
  95610. /**
  95611. * Creates a new device orientation camera
  95612. * @param name The name of the camera
  95613. * @param position The start position camera
  95614. * @param scene The scene the camera belongs to
  95615. */
  95616. function DeviceOrientationCamera(name, position, scene) {
  95617. var _this = _super.call(this, name, position, scene) || this;
  95618. _this._quaternionCache = new BABYLON.Quaternion();
  95619. _this.inputs.addDeviceOrientation();
  95620. return _this;
  95621. }
  95622. /**
  95623. * Gets the current instance class name ("DeviceOrientationCamera").
  95624. * This helps avoiding instanceof at run time.
  95625. * @returns the class name
  95626. */
  95627. DeviceOrientationCamera.prototype.getClassName = function () {
  95628. return "DeviceOrientationCamera";
  95629. };
  95630. /**
  95631. * @hidden
  95632. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  95633. */
  95634. DeviceOrientationCamera.prototype._checkInputs = function () {
  95635. _super.prototype._checkInputs.call(this);
  95636. this._quaternionCache.copyFrom(this.rotationQuaternion);
  95637. if (this._initialQuaternion) {
  95638. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  95639. }
  95640. };
  95641. /**
  95642. * Reset the camera to its default orientation on the specified axis only.
  95643. * @param axis The axis to reset
  95644. */
  95645. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  95646. var _this = this;
  95647. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  95648. //can only work if this camera has a rotation quaternion already.
  95649. if (!this.rotationQuaternion)
  95650. return;
  95651. if (!this._initialQuaternion) {
  95652. this._initialQuaternion = new BABYLON.Quaternion();
  95653. }
  95654. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  95655. ['x', 'y', 'z'].forEach(function (axisName) {
  95656. if (!axis[axisName]) {
  95657. _this._initialQuaternion[axisName] = 0;
  95658. }
  95659. else {
  95660. _this._initialQuaternion[axisName] *= -1;
  95661. }
  95662. });
  95663. this._initialQuaternion.normalize();
  95664. //force rotation update
  95665. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  95666. };
  95667. return DeviceOrientationCamera;
  95668. }(BABYLON.FreeCamera));
  95669. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  95670. })(BABYLON || (BABYLON = {}));
  95671. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  95672. var BABYLON;
  95673. (function (BABYLON) {
  95674. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  95675. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  95676. });
  95677. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  95678. __extends(VRDeviceOrientationFreeCamera, _super);
  95679. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  95680. if (compensateDistortion === void 0) { compensateDistortion = true; }
  95681. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  95682. var _this = _super.call(this, name, position, scene) || this;
  95683. vrCameraMetrics.compensateDistortion = compensateDistortion;
  95684. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  95685. return _this;
  95686. }
  95687. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  95688. return "VRDeviceOrientationFreeCamera";
  95689. };
  95690. return VRDeviceOrientationFreeCamera;
  95691. }(BABYLON.DeviceOrientationCamera));
  95692. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  95693. })(BABYLON || (BABYLON = {}));
  95694. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  95695. var BABYLON;
  95696. (function (BABYLON) {
  95697. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  95698. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  95699. });
  95700. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  95701. __extends(VRDeviceOrientationArcRotateCamera, _super);
  95702. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  95703. if (compensateDistortion === void 0) { compensateDistortion = true; }
  95704. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  95705. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  95706. vrCameraMetrics.compensateDistortion = compensateDistortion;
  95707. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  95708. _this.inputs.addVRDeviceOrientation();
  95709. return _this;
  95710. }
  95711. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  95712. return "VRDeviceOrientationArcRotateCamera";
  95713. };
  95714. return VRDeviceOrientationArcRotateCamera;
  95715. }(BABYLON.ArcRotateCamera));
  95716. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  95717. })(BABYLON || (BABYLON = {}));
  95718. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  95719. var BABYLON;
  95720. (function (BABYLON) {
  95721. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  95722. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  95723. });
  95724. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  95725. __extends(VRDeviceOrientationGamepadCamera, _super);
  95726. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  95727. if (compensateDistortion === void 0) { compensateDistortion = true; }
  95728. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  95729. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  95730. _this.inputs.addGamepad();
  95731. return _this;
  95732. }
  95733. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  95734. return "VRDeviceOrientationGamepadCamera";
  95735. };
  95736. return VRDeviceOrientationGamepadCamera;
  95737. }(BABYLON.VRDeviceOrientationFreeCamera));
  95738. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  95739. })(BABYLON || (BABYLON = {}));
  95740. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  95741. var BABYLON;
  95742. (function (BABYLON) {
  95743. var VRExperienceHelperGazer = /** @class */ (function () {
  95744. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  95745. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  95746. this.scene = scene;
  95747. /** @hidden */
  95748. this._pointerDownOnMeshAsked = false;
  95749. /** @hidden */
  95750. this._isActionableMesh = false;
  95751. /** @hidden */
  95752. this._teleportationRequestInitiated = false;
  95753. /** @hidden */
  95754. this._teleportationBackRequestInitiated = false;
  95755. /** @hidden */
  95756. this._rotationRightAsked = false;
  95757. /** @hidden */
  95758. this._rotationLeftAsked = false;
  95759. /** @hidden */
  95760. this._dpadPressed = true;
  95761. /** @hidden */
  95762. this._activePointer = false;
  95763. this._id = VRExperienceHelperGazer._idCounter++;
  95764. // Gaze tracker
  95765. if (!gazeTrackerToClone) {
  95766. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  95767. this._gazeTracker.bakeCurrentTransformIntoVertices();
  95768. this._gazeTracker.isPickable = false;
  95769. this._gazeTracker.isVisible = false;
  95770. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  95771. targetMat.specularColor = BABYLON.Color3.Black();
  95772. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  95773. targetMat.backFaceCulling = false;
  95774. this._gazeTracker.material = targetMat;
  95775. }
  95776. else {
  95777. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  95778. }
  95779. }
  95780. /** @hidden */
  95781. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  95782. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  95783. };
  95784. /** @hidden */
  95785. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  95786. this._pointerDownOnMeshAsked = true;
  95787. if (this._currentHit) {
  95788. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  95789. }
  95790. };
  95791. /** @hidden */
  95792. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  95793. if (this._currentHit) {
  95794. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  95795. }
  95796. this._pointerDownOnMeshAsked = false;
  95797. };
  95798. /** @hidden */
  95799. VRExperienceHelperGazer.prototype._activatePointer = function () {
  95800. this._activePointer = true;
  95801. };
  95802. /** @hidden */
  95803. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  95804. this._activePointer = false;
  95805. };
  95806. /** @hidden */
  95807. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  95808. if (distance === void 0) { distance = 100; }
  95809. };
  95810. VRExperienceHelperGazer.prototype.dispose = function () {
  95811. this._interactionsEnabled = false;
  95812. this._teleportationEnabled = false;
  95813. if (this._gazeTracker) {
  95814. this._gazeTracker.dispose();
  95815. }
  95816. };
  95817. VRExperienceHelperGazer._idCounter = 0;
  95818. return VRExperienceHelperGazer;
  95819. }());
  95820. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  95821. __extends(VRExperienceHelperControllerGazer, _super);
  95822. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  95823. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  95824. _this.webVRController = webVRController;
  95825. // Laser pointer
  95826. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  95827. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  95828. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  95829. laserPointerMaterial.alpha = 0.6;
  95830. _this._laserPointer.material = laserPointerMaterial;
  95831. _this._laserPointer.rotation.x = Math.PI / 2;
  95832. _this._laserPointer.position.z = -0.5;
  95833. _this._laserPointer.isVisible = false;
  95834. _this._laserPointer.isPickable = false;
  95835. if (!webVRController.mesh) {
  95836. // Create an empty mesh that is used prior to loading the high quality model
  95837. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  95838. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  95839. preloadPointerPose.rotation.x = -0.7;
  95840. preloadMesh.addChild(preloadPointerPose);
  95841. webVRController.attachToMesh(preloadMesh);
  95842. }
  95843. _this._setLaserPointerParent(webVRController.mesh);
  95844. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  95845. _this._setLaserPointerParent(mesh);
  95846. });
  95847. return _this;
  95848. }
  95849. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  95850. return this.webVRController.getForwardRay(length);
  95851. };
  95852. /** @hidden */
  95853. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  95854. _super.prototype._activatePointer.call(this);
  95855. this._laserPointer.isVisible = true;
  95856. };
  95857. /** @hidden */
  95858. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  95859. _super.prototype._deactivatePointer.call(this);
  95860. this._laserPointer.isVisible = false;
  95861. };
  95862. /** @hidden */
  95863. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  95864. this._laserPointer.material.emissiveColor = color;
  95865. };
  95866. /** @hidden */
  95867. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  95868. var makeNotPick = function (root) {
  95869. root.isPickable = false;
  95870. root.getChildMeshes().forEach(function (c) {
  95871. makeNotPick(c);
  95872. });
  95873. };
  95874. makeNotPick(mesh);
  95875. var childMeshes = mesh.getChildMeshes();
  95876. this.webVRController._pointingPoseNode = null;
  95877. for (var i = 0; i < childMeshes.length; i++) {
  95878. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  95879. mesh = childMeshes[i];
  95880. this.webVRController._pointingPoseNode = mesh;
  95881. break;
  95882. }
  95883. }
  95884. this._laserPointer.parent = mesh;
  95885. };
  95886. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  95887. if (distance === void 0) { distance = 100; }
  95888. this._laserPointer.scaling.y = distance;
  95889. this._laserPointer.position.z = -distance / 2;
  95890. };
  95891. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  95892. _super.prototype.dispose.call(this);
  95893. this._laserPointer.dispose();
  95894. if (this._meshAttachedObserver) {
  95895. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  95896. }
  95897. };
  95898. return VRExperienceHelperControllerGazer;
  95899. }(VRExperienceHelperGazer));
  95900. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  95901. __extends(VRExperienceHelperCameraGazer, _super);
  95902. function VRExperienceHelperCameraGazer(getCamera, scene) {
  95903. var _this = _super.call(this, scene) || this;
  95904. _this.getCamera = getCamera;
  95905. return _this;
  95906. }
  95907. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  95908. var camera = this.getCamera();
  95909. if (camera) {
  95910. return camera.getForwardRay(length);
  95911. }
  95912. else {
  95913. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  95914. }
  95915. };
  95916. return VRExperienceHelperCameraGazer;
  95917. }(VRExperienceHelperGazer));
  95918. /**
  95919. * Helps to quickly add VR support to an existing scene.
  95920. * See http://doc.babylonjs.com/how_to/webvr_helper
  95921. */
  95922. var VRExperienceHelper = /** @class */ (function () {
  95923. /**
  95924. * Instantiates a VRExperienceHelper.
  95925. * Helps to quickly add VR support to an existing scene.
  95926. * @param scene The scene the VRExperienceHelper belongs to.
  95927. * @param webVROptions Options to modify the vr experience helper's behavior.
  95928. */
  95929. function VRExperienceHelper(scene,
  95930. /** Options to modify the vr experience helper's behavior. */
  95931. webVROptions) {
  95932. if (webVROptions === void 0) { webVROptions = {}; }
  95933. var _this = this;
  95934. this.webVROptions = webVROptions;
  95935. // Can the system support WebVR, even if a headset isn't plugged in?
  95936. this._webVRsupported = false;
  95937. // If WebVR is supported, is a headset plugged in and are we ready to present?
  95938. this._webVRready = false;
  95939. // Are we waiting for the requestPresent callback to complete?
  95940. this._webVRrequesting = false;
  95941. // Are we presenting to the headset right now? (this is the vrDevice state)
  95942. this._webVRpresenting = false;
  95943. // Are we presenting in the fullscreen fallback?
  95944. this._fullscreenVRpresenting = false;
  95945. /**
  95946. * Observable raised when entering VR.
  95947. */
  95948. this.onEnteringVRObservable = new BABYLON.Observable();
  95949. /**
  95950. * Observable raised when exiting VR.
  95951. */
  95952. this.onExitingVRObservable = new BABYLON.Observable();
  95953. /**
  95954. * Observable raised when controller mesh is loaded.
  95955. */
  95956. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  95957. this._useCustomVRButton = false;
  95958. this._teleportationRequested = false;
  95959. this._teleportActive = false;
  95960. this._floorMeshesCollection = [];
  95961. this._rotationAllowed = true;
  95962. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  95963. this._isDefaultTeleportationTarget = true;
  95964. this._teleportationFillColor = "#444444";
  95965. this._teleportationBorderColor = "#FFFFFF";
  95966. this._rotationAngle = 0;
  95967. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  95968. this._padSensibilityUp = 0.65;
  95969. this._padSensibilityDown = 0.35;
  95970. this._leftController = null;
  95971. this._rightController = null;
  95972. /**
  95973. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  95974. */
  95975. this.onNewMeshSelected = new BABYLON.Observable();
  95976. /**
  95977. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  95978. */
  95979. this.onNewMeshPicked = new BABYLON.Observable();
  95980. /**
  95981. * Observable raised before camera teleportation
  95982. */
  95983. this.onBeforeCameraTeleport = new BABYLON.Observable();
  95984. /**
  95985. * Observable raised after camera teleportation
  95986. */
  95987. this.onAfterCameraTeleport = new BABYLON.Observable();
  95988. /**
  95989. * Observable raised when current selected mesh gets unselected
  95990. */
  95991. this.onSelectedMeshUnselected = new BABYLON.Observable();
  95992. /**
  95993. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  95994. */
  95995. this.teleportationEnabled = true;
  95996. this._teleportationInitialized = false;
  95997. this._interactionsEnabled = false;
  95998. this._interactionsRequested = false;
  95999. this._displayGaze = true;
  96000. this._displayLaserPointer = true;
  96001. /**
  96002. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  96003. */
  96004. this.updateGazeTrackerScale = true;
  96005. this._onResize = function () {
  96006. _this.moveButtonToBottomRight();
  96007. if (_this._fullscreenVRpresenting && _this._webVRready) {
  96008. _this.exitVR();
  96009. }
  96010. };
  96011. this._onFullscreenChange = function () {
  96012. if (document.fullscreen !== undefined) {
  96013. _this._fullscreenVRpresenting = document.fullscreen;
  96014. }
  96015. else if (document.mozFullScreen !== undefined) {
  96016. _this._fullscreenVRpresenting = document.mozFullScreen;
  96017. }
  96018. else if (document.webkitIsFullScreen !== undefined) {
  96019. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  96020. }
  96021. else if (document.msIsFullScreen !== undefined) {
  96022. _this._fullscreenVRpresenting = document.msIsFullScreen;
  96023. }
  96024. else if (document.msFullscreenElement !== undefined) {
  96025. _this._fullscreenVRpresenting = document.msFullscreenElement;
  96026. }
  96027. if (!_this._fullscreenVRpresenting && _this._canvas) {
  96028. _this.exitVR();
  96029. if (!_this._useCustomVRButton) {
  96030. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  96031. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  96032. }
  96033. }
  96034. };
  96035. this.beforeRender = function () {
  96036. if (_this._leftController && _this._leftController._activePointer) {
  96037. _this._castRayAndSelectObject(_this._leftController);
  96038. }
  96039. if (_this._rightController && _this._rightController._activePointer) {
  96040. _this._castRayAndSelectObject(_this._rightController);
  96041. }
  96042. if (_this._noControllerIsActive) {
  96043. _this._castRayAndSelectObject(_this._cameraGazer);
  96044. }
  96045. else {
  96046. _this._cameraGazer._gazeTracker.isVisible = false;
  96047. }
  96048. };
  96049. this._onNewGamepadConnected = function (gamepad) {
  96050. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  96051. if (gamepad.leftStick) {
  96052. gamepad.onleftstickchanged(function (stickValues) {
  96053. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  96054. // Listening to classic/xbox gamepad only if no VR controller is active
  96055. if ((!_this._leftController && !_this._rightController) ||
  96056. ((_this._leftController && !_this._leftController._activePointer) &&
  96057. (_this._rightController && !_this._rightController._activePointer))) {
  96058. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  96059. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  96060. }
  96061. }
  96062. });
  96063. }
  96064. if (gamepad.rightStick) {
  96065. gamepad.onrightstickchanged(function (stickValues) {
  96066. if (_this._teleportationInitialized) {
  96067. _this._checkRotate(stickValues, _this._cameraGazer);
  96068. }
  96069. });
  96070. }
  96071. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  96072. gamepad.onbuttondown(function (buttonPressed) {
  96073. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  96074. _this._cameraGazer._selectionPointerDown();
  96075. }
  96076. });
  96077. gamepad.onbuttonup(function (buttonPressed) {
  96078. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  96079. _this._cameraGazer._selectionPointerUp();
  96080. }
  96081. });
  96082. }
  96083. }
  96084. else {
  96085. var webVRController = gamepad;
  96086. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  96087. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  96088. _this._rightController = controller;
  96089. }
  96090. else {
  96091. _this._leftController = controller;
  96092. }
  96093. _this._tryEnableInteractionOnController(controller);
  96094. }
  96095. };
  96096. // 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
  96097. this._tryEnableInteractionOnController = function (controller) {
  96098. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  96099. _this._enableInteractionOnController(controller);
  96100. }
  96101. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  96102. _this._enableTeleportationOnController(controller);
  96103. }
  96104. };
  96105. this._onNewGamepadDisconnected = function (gamepad) {
  96106. if (gamepad instanceof BABYLON.WebVRController) {
  96107. if (gamepad.hand === "left" && _this._leftController != null) {
  96108. _this._leftController.dispose();
  96109. _this._leftController = null;
  96110. }
  96111. if (gamepad.hand === "right" && _this._rightController != null) {
  96112. _this._rightController.dispose();
  96113. _this._rightController = null;
  96114. }
  96115. }
  96116. };
  96117. this._workingVector = BABYLON.Vector3.Zero();
  96118. this._workingQuaternion = BABYLON.Quaternion.Identity();
  96119. this._workingMatrix = BABYLON.Matrix.Identity();
  96120. this._scene = scene;
  96121. this._canvas = scene.getEngine().getRenderingCanvas();
  96122. // Parse options
  96123. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  96124. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  96125. }
  96126. if (webVROptions.createDeviceOrientationCamera === undefined) {
  96127. webVROptions.createDeviceOrientationCamera = true;
  96128. }
  96129. if (webVROptions.laserToggle === undefined) {
  96130. webVROptions.laserToggle = true;
  96131. }
  96132. if (webVROptions.defaultHeight === undefined) {
  96133. webVROptions.defaultHeight = 1.7;
  96134. }
  96135. if (webVROptions.useCustomVRButton) {
  96136. this._useCustomVRButton = true;
  96137. if (webVROptions.customVRButton) {
  96138. this._btnVR = webVROptions.customVRButton;
  96139. }
  96140. }
  96141. if (webVROptions.rayLength) {
  96142. this._rayLength = webVROptions.rayLength;
  96143. }
  96144. this._defaultHeight = webVROptions.defaultHeight;
  96145. if (webVROptions.positionScale) {
  96146. this._rayLength *= webVROptions.positionScale;
  96147. this._defaultHeight *= webVROptions.positionScale;
  96148. }
  96149. this._hasEnteredVR = false;
  96150. // Set position
  96151. if (this._scene.activeCamera) {
  96152. this._position = this._scene.activeCamera.position.clone();
  96153. }
  96154. else {
  96155. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  96156. }
  96157. // Set non-vr camera
  96158. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  96159. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  96160. // Copy data from existing camera
  96161. if (this._scene.activeCamera) {
  96162. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  96163. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  96164. // Set rotation from previous camera
  96165. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  96166. var targetCamera = this._scene.activeCamera;
  96167. if (targetCamera.rotationQuaternion) {
  96168. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  96169. }
  96170. else {
  96171. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  96172. }
  96173. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  96174. }
  96175. }
  96176. this._scene.activeCamera = this._deviceOrientationCamera;
  96177. if (this._canvas) {
  96178. this._scene.activeCamera.attachControl(this._canvas);
  96179. }
  96180. }
  96181. else {
  96182. this._existingCamera = this._scene.activeCamera;
  96183. }
  96184. // Create VR cameras
  96185. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  96186. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  96187. }
  96188. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  96189. this._webVRCamera.useStandingMatrix();
  96190. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  96191. // Create default button
  96192. if (!this._useCustomVRButton) {
  96193. this._btnVR = document.createElement("BUTTON");
  96194. this._btnVR.className = "babylonVRicon";
  96195. this._btnVR.id = "babylonVRiconbtn";
  96196. this._btnVR.title = "Click to switch to VR";
  96197. 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) }";
  96198. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  96199. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  96200. // css += ".babylonVRicon.vrdisplaysupported { }";
  96201. // css += ".babylonVRicon.vrdisplayready { }";
  96202. // css += ".babylonVRicon.vrdisplayrequesting { }";
  96203. var style = document.createElement('style');
  96204. style.appendChild(document.createTextNode(css));
  96205. document.getElementsByTagName('head')[0].appendChild(style);
  96206. this.moveButtonToBottomRight();
  96207. }
  96208. // VR button click event
  96209. if (this._btnVR) {
  96210. this._btnVR.addEventListener("click", function () {
  96211. if (!_this.isInVRMode) {
  96212. _this.enterVR();
  96213. }
  96214. else {
  96215. _this.exitVR();
  96216. }
  96217. });
  96218. }
  96219. // Window events
  96220. window.addEventListener("resize", this._onResize);
  96221. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  96222. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  96223. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  96224. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  96225. document.onmsfullscreenchange = this._onFullscreenChange;
  96226. // Display vr button when headset is connected
  96227. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  96228. this.displayVRButton();
  96229. }
  96230. else {
  96231. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  96232. if (e.vrDisplay) {
  96233. _this.displayVRButton();
  96234. }
  96235. });
  96236. }
  96237. // Exiting VR mode using 'ESC' key on desktop
  96238. this._onKeyDown = function (event) {
  96239. if (event.keyCode === 27 && _this.isInVRMode) {
  96240. _this.exitVR();
  96241. }
  96242. };
  96243. document.addEventListener("keydown", this._onKeyDown);
  96244. // Exiting VR mode double tapping the touch screen
  96245. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  96246. if (_this.isInVRMode) {
  96247. _this.exitVR();
  96248. if (_this._fullscreenVRpresenting) {
  96249. _this._scene.getEngine().switchFullscreen(true);
  96250. }
  96251. }
  96252. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  96253. // Listen for WebVR display changes
  96254. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  96255. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  96256. this._onVRRequestPresentStart = function () {
  96257. _this._webVRrequesting = true;
  96258. _this.updateButtonVisibility();
  96259. };
  96260. this._onVRRequestPresentComplete = function (success) {
  96261. _this._webVRrequesting = false;
  96262. _this.updateButtonVisibility();
  96263. };
  96264. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  96265. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  96266. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  96267. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  96268. scene.onDisposeObservable.add(function () {
  96269. _this.dispose();
  96270. });
  96271. // Gamepad connection events
  96272. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  96273. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  96274. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  96275. this.updateButtonVisibility();
  96276. //create easing functions
  96277. this._circleEase = new BABYLON.CircleEase();
  96278. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  96279. if (this.webVROptions.floorMeshes) {
  96280. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  96281. }
  96282. }
  96283. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  96284. /** Return this.onEnteringVRObservable
  96285. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  96286. */
  96287. get: function () {
  96288. return this.onEnteringVRObservable;
  96289. },
  96290. enumerable: true,
  96291. configurable: true
  96292. });
  96293. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  96294. /** Return this.onExitingVRObservable
  96295. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  96296. */
  96297. get: function () {
  96298. return this.onExitingVRObservable;
  96299. },
  96300. enumerable: true,
  96301. configurable: true
  96302. });
  96303. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  96304. /** Return this.onControllerMeshLoadedObservable
  96305. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  96306. */
  96307. get: function () {
  96308. return this.onControllerMeshLoadedObservable;
  96309. },
  96310. enumerable: true,
  96311. configurable: true
  96312. });
  96313. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  96314. /**
  96315. * The mesh used to display where the user is going to teleport.
  96316. */
  96317. get: function () {
  96318. return this._teleportationTarget;
  96319. },
  96320. /**
  96321. * Sets the mesh to be used to display where the user is going to teleport.
  96322. */
  96323. set: function (value) {
  96324. if (value) {
  96325. value.name = "teleportationTarget";
  96326. this._isDefaultTeleportationTarget = false;
  96327. this._teleportationTarget = value;
  96328. }
  96329. },
  96330. enumerable: true,
  96331. configurable: true
  96332. });
  96333. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  96334. /**
  96335. * 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
  96336. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  96337. * See http://doc.babylonjs.com/resources/baking_transformations
  96338. */
  96339. get: function () {
  96340. return this._cameraGazer._gazeTracker;
  96341. },
  96342. set: function (value) {
  96343. if (value) {
  96344. // Dispose of existing meshes
  96345. if (this._cameraGazer._gazeTracker) {
  96346. this._cameraGazer._gazeTracker.dispose();
  96347. }
  96348. if (this._leftController && this._leftController._gazeTracker) {
  96349. this._leftController._gazeTracker.dispose();
  96350. }
  96351. if (this._rightController && this._rightController._gazeTracker) {
  96352. this._rightController._gazeTracker.dispose();
  96353. }
  96354. // Set and create gaze trackers on head and controllers
  96355. this._cameraGazer._gazeTracker = value;
  96356. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  96357. this._cameraGazer._gazeTracker.isPickable = false;
  96358. this._cameraGazer._gazeTracker.isVisible = false;
  96359. this._cameraGazer._gazeTracker.name = "gazeTracker";
  96360. if (this._leftController) {
  96361. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  96362. }
  96363. if (this._rightController) {
  96364. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  96365. }
  96366. }
  96367. },
  96368. enumerable: true,
  96369. configurable: true
  96370. });
  96371. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  96372. /**
  96373. * The gaze tracking mesh corresponding to the left controller
  96374. */
  96375. get: function () {
  96376. if (this._leftController) {
  96377. return this._leftController._gazeTracker;
  96378. }
  96379. return null;
  96380. },
  96381. enumerable: true,
  96382. configurable: true
  96383. });
  96384. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  96385. /**
  96386. * The gaze tracking mesh corresponding to the right controller
  96387. */
  96388. get: function () {
  96389. if (this._rightController) {
  96390. return this._rightController._gazeTracker;
  96391. }
  96392. return null;
  96393. },
  96394. enumerable: true,
  96395. configurable: true
  96396. });
  96397. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  96398. /**
  96399. * If the ray of the gaze should be displayed.
  96400. */
  96401. get: function () {
  96402. return this._displayGaze;
  96403. },
  96404. /**
  96405. * Sets if the ray of the gaze should be displayed.
  96406. */
  96407. set: function (value) {
  96408. this._displayGaze = value;
  96409. if (!value) {
  96410. this._cameraGazer._gazeTracker.isVisible = false;
  96411. if (this._leftController) {
  96412. this._leftController._gazeTracker.isVisible = false;
  96413. }
  96414. if (this._rightController) {
  96415. this._rightController._gazeTracker.isVisible = false;
  96416. }
  96417. }
  96418. },
  96419. enumerable: true,
  96420. configurable: true
  96421. });
  96422. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  96423. /**
  96424. * If the ray of the LaserPointer should be displayed.
  96425. */
  96426. get: function () {
  96427. return this._displayLaserPointer;
  96428. },
  96429. /**
  96430. * Sets if the ray of the LaserPointer should be displayed.
  96431. */
  96432. set: function (value) {
  96433. this._displayLaserPointer = value;
  96434. if (!value) {
  96435. if (this._rightController) {
  96436. this._rightController._deactivatePointer();
  96437. this._rightController._gazeTracker.isVisible = false;
  96438. }
  96439. if (this._leftController) {
  96440. this._leftController._deactivatePointer();
  96441. this._leftController._gazeTracker.isVisible = false;
  96442. }
  96443. }
  96444. else {
  96445. if (this._rightController) {
  96446. this._rightController._activatePointer();
  96447. }
  96448. if (this._leftController) {
  96449. this._leftController._activatePointer();
  96450. }
  96451. }
  96452. },
  96453. enumerable: true,
  96454. configurable: true
  96455. });
  96456. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  96457. /**
  96458. * The deviceOrientationCamera used as the camera when not in VR.
  96459. */
  96460. get: function () {
  96461. return this._deviceOrientationCamera;
  96462. },
  96463. enumerable: true,
  96464. configurable: true
  96465. });
  96466. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  96467. /**
  96468. * Based on the current WebVR support, returns the current VR camera used.
  96469. */
  96470. get: function () {
  96471. if (this._webVRready) {
  96472. return this._webVRCamera;
  96473. }
  96474. else {
  96475. return this._scene.activeCamera;
  96476. }
  96477. },
  96478. enumerable: true,
  96479. configurable: true
  96480. });
  96481. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  96482. /**
  96483. * The webVRCamera which is used when in VR.
  96484. */
  96485. get: function () {
  96486. return this._webVRCamera;
  96487. },
  96488. enumerable: true,
  96489. configurable: true
  96490. });
  96491. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  96492. /**
  96493. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  96494. */
  96495. get: function () {
  96496. return this._vrDeviceOrientationCamera;
  96497. },
  96498. enumerable: true,
  96499. configurable: true
  96500. });
  96501. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  96502. get: function () {
  96503. var result = this._cameraGazer._teleportationRequestInitiated
  96504. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  96505. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  96506. return result;
  96507. },
  96508. enumerable: true,
  96509. configurable: true
  96510. });
  96511. // Raised when one of the controller has loaded successfully its associated default mesh
  96512. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  96513. if (this._leftController && this._leftController.webVRController == webVRController) {
  96514. if (webVRController.mesh) {
  96515. this._leftController._setLaserPointerParent(webVRController.mesh);
  96516. }
  96517. }
  96518. if (this._rightController && this._rightController.webVRController == webVRController) {
  96519. if (webVRController.mesh) {
  96520. this._rightController._setLaserPointerParent(webVRController.mesh);
  96521. }
  96522. }
  96523. try {
  96524. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  96525. }
  96526. catch (err) {
  96527. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  96528. }
  96529. };
  96530. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  96531. /**
  96532. * Gets a value indicating if we are currently in VR mode.
  96533. */
  96534. get: function () {
  96535. return this._webVRpresenting || this._fullscreenVRpresenting;
  96536. },
  96537. enumerable: true,
  96538. configurable: true
  96539. });
  96540. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  96541. var vrDisplay = this._scene.getEngine().getVRDevice();
  96542. if (vrDisplay) {
  96543. var wasPresenting = this._webVRpresenting;
  96544. this._webVRpresenting = vrDisplay.isPresenting;
  96545. if (wasPresenting && !this._webVRpresenting)
  96546. this.exitVR();
  96547. }
  96548. else {
  96549. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  96550. }
  96551. this.updateButtonVisibility();
  96552. };
  96553. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  96554. this._webVRsupported = eventArgs.vrSupported;
  96555. this._webVRready = !!eventArgs.vrDisplay;
  96556. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  96557. this.updateButtonVisibility();
  96558. };
  96559. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  96560. if (this._canvas && !this._useCustomVRButton) {
  96561. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  96562. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  96563. }
  96564. };
  96565. VRExperienceHelper.prototype.displayVRButton = function () {
  96566. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  96567. document.body.appendChild(this._btnVR);
  96568. this._btnVRDisplayed = true;
  96569. }
  96570. };
  96571. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  96572. if (!this._btnVR || this._useCustomVRButton) {
  96573. return;
  96574. }
  96575. this._btnVR.className = "babylonVRicon";
  96576. if (this.isInVRMode) {
  96577. this._btnVR.className += " vrdisplaypresenting";
  96578. }
  96579. else {
  96580. if (this._webVRready)
  96581. this._btnVR.className += " vrdisplayready";
  96582. if (this._webVRsupported)
  96583. this._btnVR.className += " vrdisplaysupported";
  96584. if (this._webVRrequesting)
  96585. this._btnVR.className += " vrdisplayrequesting";
  96586. }
  96587. };
  96588. /**
  96589. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  96590. * Otherwise, will use the fullscreen API.
  96591. */
  96592. VRExperienceHelper.prototype.enterVR = function () {
  96593. if (this.onEnteringVRObservable) {
  96594. try {
  96595. this.onEnteringVRObservable.notifyObservers(this);
  96596. }
  96597. catch (err) {
  96598. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  96599. }
  96600. }
  96601. if (this._scene.activeCamera) {
  96602. this._position = this._scene.activeCamera.position.clone();
  96603. // make sure that we return to the last active camera
  96604. this._existingCamera = this._scene.activeCamera;
  96605. }
  96606. if (this._webVRrequesting)
  96607. return;
  96608. // If WebVR is supported and a headset is connected
  96609. if (this._webVRready) {
  96610. if (!this._webVRpresenting) {
  96611. this._webVRCamera.position = this._position;
  96612. this._scene.activeCamera = this._webVRCamera;
  96613. }
  96614. }
  96615. else if (this._vrDeviceOrientationCamera) {
  96616. this._vrDeviceOrientationCamera.position = this._position;
  96617. if (this._scene.activeCamera) {
  96618. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  96619. }
  96620. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  96621. this._scene.getEngine().switchFullscreen(true);
  96622. this.updateButtonVisibility();
  96623. }
  96624. if (this._scene.activeCamera && this._canvas) {
  96625. this._scene.activeCamera.attachControl(this._canvas);
  96626. }
  96627. if (this._interactionsEnabled) {
  96628. this._scene.registerBeforeRender(this.beforeRender);
  96629. }
  96630. this._hasEnteredVR = true;
  96631. };
  96632. /**
  96633. * Attempt to exit VR, or fullscreen.
  96634. */
  96635. VRExperienceHelper.prototype.exitVR = function () {
  96636. if (this._hasEnteredVR) {
  96637. if (this.onExitingVRObservable) {
  96638. try {
  96639. this.onExitingVRObservable.notifyObservers(this);
  96640. }
  96641. catch (err) {
  96642. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  96643. }
  96644. }
  96645. if (this._webVRpresenting) {
  96646. this._scene.getEngine().disableVR();
  96647. }
  96648. if (this._scene.activeCamera) {
  96649. this._position = this._scene.activeCamera.position.clone();
  96650. }
  96651. if (this._deviceOrientationCamera) {
  96652. this._deviceOrientationCamera.position = this._position;
  96653. this._scene.activeCamera = this._deviceOrientationCamera;
  96654. if (this._canvas) {
  96655. this._scene.activeCamera.attachControl(this._canvas);
  96656. }
  96657. }
  96658. else if (this._existingCamera) {
  96659. this._existingCamera.position = this._position;
  96660. this._scene.activeCamera = this._existingCamera;
  96661. }
  96662. this.updateButtonVisibility();
  96663. if (this._interactionsEnabled) {
  96664. this._scene.unregisterBeforeRender(this.beforeRender);
  96665. this._cameraGazer._gazeTracker.isVisible = false;
  96666. if (this._leftController) {
  96667. this._leftController._gazeTracker.isVisible = false;
  96668. }
  96669. if (this._rightController) {
  96670. this._rightController._gazeTracker.isVisible = false;
  96671. }
  96672. }
  96673. // resize to update width and height when exiting vr exits fullscreen
  96674. this._scene.getEngine().resize();
  96675. this._hasEnteredVR = false;
  96676. }
  96677. };
  96678. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  96679. /**
  96680. * The position of the vr experience helper.
  96681. */
  96682. get: function () {
  96683. return this._position;
  96684. },
  96685. /**
  96686. * Sets the position of the vr experience helper.
  96687. */
  96688. set: function (value) {
  96689. this._position = value;
  96690. if (this._scene.activeCamera) {
  96691. this._scene.activeCamera.position = value;
  96692. }
  96693. },
  96694. enumerable: true,
  96695. configurable: true
  96696. });
  96697. /**
  96698. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  96699. */
  96700. VRExperienceHelper.prototype.enableInteractions = function () {
  96701. var _this = this;
  96702. if (!this._interactionsEnabled) {
  96703. this._interactionsRequested = true;
  96704. if (this._leftController) {
  96705. this._enableInteractionOnController(this._leftController);
  96706. }
  96707. if (this._rightController) {
  96708. this._enableInteractionOnController(this._rightController);
  96709. }
  96710. this.raySelectionPredicate = function (mesh) {
  96711. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  96712. };
  96713. this.meshSelectionPredicate = function (mesh) {
  96714. return true;
  96715. };
  96716. this._raySelectionPredicate = function (mesh) {
  96717. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  96718. && mesh.name.indexOf("teleportationTarget") === -1
  96719. && mesh.name.indexOf("torusTeleportation") === -1)) {
  96720. return _this.raySelectionPredicate(mesh);
  96721. }
  96722. return false;
  96723. };
  96724. this._interactionsEnabled = true;
  96725. }
  96726. };
  96727. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  96728. get: function () {
  96729. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  96730. },
  96731. enumerable: true,
  96732. configurable: true
  96733. });
  96734. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  96735. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  96736. if (this._floorMeshesCollection[i].id === mesh.id) {
  96737. return true;
  96738. }
  96739. }
  96740. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  96741. return true;
  96742. }
  96743. return false;
  96744. };
  96745. /**
  96746. * Adds a floor mesh to be used for teleportation.
  96747. * @param floorMesh the mesh to be used for teleportation.
  96748. */
  96749. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  96750. if (!this._floorMeshesCollection) {
  96751. return;
  96752. }
  96753. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  96754. return;
  96755. }
  96756. this._floorMeshesCollection.push(floorMesh);
  96757. };
  96758. /**
  96759. * Removes a floor mesh from being used for teleportation.
  96760. * @param floorMesh the mesh to be removed.
  96761. */
  96762. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  96763. if (!this._floorMeshesCollection) {
  96764. return;
  96765. }
  96766. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  96767. if (meshIndex !== -1) {
  96768. this._floorMeshesCollection.splice(meshIndex, 1);
  96769. }
  96770. };
  96771. /**
  96772. * Enables interactions and teleportation using the VR controllers and gaze.
  96773. * @param vrTeleportationOptions options to modify teleportation behavior.
  96774. */
  96775. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  96776. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  96777. if (!this._teleportationInitialized) {
  96778. this._teleportationRequested = true;
  96779. this.enableInteractions();
  96780. if (vrTeleportationOptions.floorMeshName) {
  96781. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  96782. }
  96783. if (vrTeleportationOptions.floorMeshes) {
  96784. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  96785. }
  96786. if (this._leftController != null) {
  96787. this._enableTeleportationOnController(this._leftController);
  96788. }
  96789. if (this._rightController != null) {
  96790. this._enableTeleportationOnController(this._rightController);
  96791. }
  96792. // Creates an image processing post process for the vignette not relying
  96793. // on the main scene configuration for image processing to reduce setup and spaces
  96794. // (gamma/linear) conflicts.
  96795. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  96796. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  96797. imageProcessingConfiguration.vignetteEnabled = true;
  96798. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  96799. this._webVRCamera.detachPostProcess(this._postProcessMove);
  96800. this._teleportationInitialized = true;
  96801. if (this._isDefaultTeleportationTarget) {
  96802. this._createTeleportationCircles();
  96803. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  96804. }
  96805. }
  96806. };
  96807. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  96808. var _this = this;
  96809. var controllerMesh = controller.webVRController.mesh;
  96810. if (controllerMesh) {
  96811. controller._interactionsEnabled = true;
  96812. controller._activatePointer();
  96813. if (this.webVROptions.laserToggle) {
  96814. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  96815. // Enabling / disabling laserPointer
  96816. if (_this._displayLaserPointer && stateObject.value === 1) {
  96817. if (controller._activePointer) {
  96818. controller._deactivatePointer();
  96819. }
  96820. else {
  96821. controller._activatePointer();
  96822. }
  96823. if (_this.displayGaze) {
  96824. controller._gazeTracker.isVisible = controller._activePointer;
  96825. }
  96826. }
  96827. });
  96828. }
  96829. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  96830. var gazer = controller;
  96831. if (_this._noControllerIsActive) {
  96832. gazer = _this._cameraGazer;
  96833. }
  96834. if (!gazer._pointerDownOnMeshAsked) {
  96835. if (stateObject.value > _this._padSensibilityUp) {
  96836. gazer._selectionPointerDown();
  96837. }
  96838. }
  96839. else if (stateObject.value < _this._padSensibilityDown) {
  96840. gazer._selectionPointerUp();
  96841. }
  96842. });
  96843. }
  96844. };
  96845. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  96846. // Dont teleport if another gaze already requested teleportation
  96847. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  96848. return;
  96849. }
  96850. if (!gazer._teleportationRequestInitiated) {
  96851. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  96852. gazer._activatePointer();
  96853. gazer._teleportationRequestInitiated = true;
  96854. }
  96855. }
  96856. else {
  96857. // Listening to the proper controller values changes to confirm teleportation
  96858. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  96859. if (this._teleportActive) {
  96860. this._teleportCamera(this._haloCenter);
  96861. }
  96862. gazer._teleportationRequestInitiated = false;
  96863. }
  96864. }
  96865. };
  96866. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  96867. // Only rotate when user is not currently selecting a teleportation location
  96868. if (gazer._teleportationRequestInitiated) {
  96869. return;
  96870. }
  96871. if (!gazer._rotationLeftAsked) {
  96872. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  96873. gazer._rotationLeftAsked = true;
  96874. if (this._rotationAllowed) {
  96875. this._rotateCamera(false);
  96876. }
  96877. }
  96878. }
  96879. else {
  96880. if (stateObject.x > -this._padSensibilityDown) {
  96881. gazer._rotationLeftAsked = false;
  96882. }
  96883. }
  96884. if (!gazer._rotationRightAsked) {
  96885. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  96886. gazer._rotationRightAsked = true;
  96887. if (this._rotationAllowed) {
  96888. this._rotateCamera(true);
  96889. }
  96890. }
  96891. }
  96892. else {
  96893. if (stateObject.x < this._padSensibilityDown) {
  96894. gazer._rotationRightAsked = false;
  96895. }
  96896. }
  96897. };
  96898. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  96899. // Only teleport backwards when user is not currently selecting a teleportation location
  96900. if (gazer._teleportationRequestInitiated) {
  96901. return;
  96902. }
  96903. // Teleport backwards
  96904. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  96905. if (!gazer._teleportationBackRequestInitiated) {
  96906. if (!this.currentVRCamera) {
  96907. return;
  96908. }
  96909. // Get rotation and position of the current camera
  96910. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  96911. var position = this.currentVRCamera.position;
  96912. // If the camera has device position, use that instead
  96913. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  96914. rotation = this.currentVRCamera.deviceRotationQuaternion;
  96915. position = this.currentVRCamera.devicePosition;
  96916. }
  96917. // Get matrix with only the y rotation of the device rotation
  96918. rotation.toEulerAnglesToRef(this._workingVector);
  96919. this._workingVector.z = 0;
  96920. this._workingVector.x = 0;
  96921. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  96922. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  96923. // Rotate backwards ray by device rotation to cast at the ground behind the user
  96924. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  96925. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  96926. var ray = new BABYLON.Ray(position, this._workingVector);
  96927. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  96928. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  96929. this._teleportCamera(hit.pickedPoint);
  96930. }
  96931. gazer._teleportationBackRequestInitiated = true;
  96932. }
  96933. }
  96934. else {
  96935. gazer._teleportationBackRequestInitiated = false;
  96936. }
  96937. };
  96938. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  96939. var _this = this;
  96940. var controllerMesh = controller.webVRController.mesh;
  96941. if (controllerMesh) {
  96942. if (!controller._interactionsEnabled) {
  96943. this._enableInteractionOnController(controller);
  96944. }
  96945. controller._interactionsEnabled = true;
  96946. controller._teleportationEnabled = true;
  96947. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  96948. controller._dpadPressed = false;
  96949. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  96950. controller._dpadPressed = stateObject.pressed;
  96951. if (!controller._dpadPressed) {
  96952. controller._rotationLeftAsked = false;
  96953. controller._rotationRightAsked = false;
  96954. controller._teleportationBackRequestInitiated = false;
  96955. }
  96956. });
  96957. }
  96958. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  96959. if (_this.teleportationEnabled) {
  96960. _this._checkTeleportBackwards(stateObject, controller);
  96961. _this._checkTeleportWithRay(stateObject, controller);
  96962. }
  96963. _this._checkRotate(stateObject, controller);
  96964. });
  96965. }
  96966. };
  96967. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  96968. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  96969. this._teleportationTarget.isPickable = false;
  96970. var length = 512;
  96971. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  96972. dynamicTexture.hasAlpha = true;
  96973. var context = dynamicTexture.getContext();
  96974. var centerX = length / 2;
  96975. var centerY = length / 2;
  96976. var radius = 200;
  96977. context.beginPath();
  96978. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  96979. context.fillStyle = this._teleportationFillColor;
  96980. context.fill();
  96981. context.lineWidth = 10;
  96982. context.strokeStyle = this._teleportationBorderColor;
  96983. context.stroke();
  96984. context.closePath();
  96985. dynamicTexture.update();
  96986. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  96987. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  96988. this._teleportationTarget.material = teleportationCircleMaterial;
  96989. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  96990. torus.isPickable = false;
  96991. torus.parent = this._teleportationTarget;
  96992. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  96993. var keys = [];
  96994. keys.push({
  96995. frame: 0,
  96996. value: 0
  96997. });
  96998. keys.push({
  96999. frame: 30,
  97000. value: 0.4
  97001. });
  97002. keys.push({
  97003. frame: 60,
  97004. value: 0
  97005. });
  97006. animationInnerCircle.setKeys(keys);
  97007. var easingFunction = new BABYLON.SineEase();
  97008. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  97009. animationInnerCircle.setEasingFunction(easingFunction);
  97010. torus.animations = [];
  97011. torus.animations.push(animationInnerCircle);
  97012. this._scene.beginAnimation(torus, 0, 60, true);
  97013. this._hideTeleportationTarget();
  97014. };
  97015. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  97016. this._teleportActive = true;
  97017. if (this._teleportationInitialized) {
  97018. this._teleportationTarget.isVisible = true;
  97019. if (this._isDefaultTeleportationTarget) {
  97020. this._teleportationTarget.getChildren()[0].isVisible = true;
  97021. }
  97022. }
  97023. };
  97024. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  97025. this._teleportActive = false;
  97026. if (this._teleportationInitialized) {
  97027. this._teleportationTarget.isVisible = false;
  97028. if (this._isDefaultTeleportationTarget) {
  97029. this._teleportationTarget.getChildren()[0].isVisible = false;
  97030. }
  97031. }
  97032. };
  97033. VRExperienceHelper.prototype._rotateCamera = function (right) {
  97034. var _this = this;
  97035. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  97036. return;
  97037. }
  97038. if (right) {
  97039. this._rotationAngle++;
  97040. }
  97041. else {
  97042. this._rotationAngle--;
  97043. }
  97044. this.currentVRCamera.animations = [];
  97045. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  97046. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  97047. var animationRotationKeys = [];
  97048. animationRotationKeys.push({
  97049. frame: 0,
  97050. value: this.currentVRCamera.rotationQuaternion
  97051. });
  97052. animationRotationKeys.push({
  97053. frame: 6,
  97054. value: target
  97055. });
  97056. animationRotation.setKeys(animationRotationKeys);
  97057. animationRotation.setEasingFunction(this._circleEase);
  97058. this.currentVRCamera.animations.push(animationRotation);
  97059. this._postProcessMove.animations = [];
  97060. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  97061. var vignetteWeightKeys = [];
  97062. vignetteWeightKeys.push({
  97063. frame: 0,
  97064. value: 0
  97065. });
  97066. vignetteWeightKeys.push({
  97067. frame: 3,
  97068. value: 4
  97069. });
  97070. vignetteWeightKeys.push({
  97071. frame: 6,
  97072. value: 0
  97073. });
  97074. animationPP.setKeys(vignetteWeightKeys);
  97075. animationPP.setEasingFunction(this._circleEase);
  97076. this._postProcessMove.animations.push(animationPP);
  97077. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  97078. var vignetteStretchKeys = [];
  97079. vignetteStretchKeys.push({
  97080. frame: 0,
  97081. value: 0
  97082. });
  97083. vignetteStretchKeys.push({
  97084. frame: 3,
  97085. value: 10
  97086. });
  97087. vignetteStretchKeys.push({
  97088. frame: 6,
  97089. value: 0
  97090. });
  97091. animationPP2.setKeys(vignetteStretchKeys);
  97092. animationPP2.setEasingFunction(this._circleEase);
  97093. this._postProcessMove.animations.push(animationPP2);
  97094. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  97095. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  97096. this._postProcessMove.samples = 4;
  97097. this._webVRCamera.attachPostProcess(this._postProcessMove);
  97098. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  97099. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  97100. });
  97101. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  97102. };
  97103. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  97104. if (hit.pickedPoint) {
  97105. if (gazer._teleportationRequestInitiated) {
  97106. this._displayTeleportationTarget();
  97107. this._haloCenter.copyFrom(hit.pickedPoint);
  97108. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  97109. }
  97110. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  97111. if (pickNormal) {
  97112. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  97113. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  97114. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  97115. }
  97116. this._teleportationTarget.position.y += 0.1;
  97117. }
  97118. };
  97119. VRExperienceHelper.prototype._teleportCamera = function (location) {
  97120. var _this = this;
  97121. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  97122. return;
  97123. }
  97124. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  97125. // offset of the headset from the anchor.
  97126. if (this.webVRCamera.leftCamera) {
  97127. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  97128. this._workingVector.subtractInPlace(this.webVRCamera.position);
  97129. location.subtractToRef(this._workingVector, this._workingVector);
  97130. }
  97131. else {
  97132. this._workingVector.copyFrom(location);
  97133. }
  97134. // Add height to account for user's height offset
  97135. if (this.isInVRMode) {
  97136. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  97137. }
  97138. else {
  97139. this._workingVector.y += this._defaultHeight;
  97140. }
  97141. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  97142. // Create animation from the camera's position to the new location
  97143. this.currentVRCamera.animations = [];
  97144. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  97145. var animationCameraTeleportationKeys = [{
  97146. frame: 0,
  97147. value: this.currentVRCamera.position
  97148. },
  97149. {
  97150. frame: 11,
  97151. value: this._workingVector
  97152. }
  97153. ];
  97154. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  97155. animationCameraTeleportation.setEasingFunction(this._circleEase);
  97156. this.currentVRCamera.animations.push(animationCameraTeleportation);
  97157. this._postProcessMove.animations = [];
  97158. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  97159. var vignetteWeightKeys = [];
  97160. vignetteWeightKeys.push({
  97161. frame: 0,
  97162. value: 0
  97163. });
  97164. vignetteWeightKeys.push({
  97165. frame: 5,
  97166. value: 8
  97167. });
  97168. vignetteWeightKeys.push({
  97169. frame: 11,
  97170. value: 0
  97171. });
  97172. animationPP.setKeys(vignetteWeightKeys);
  97173. this._postProcessMove.animations.push(animationPP);
  97174. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  97175. var vignetteStretchKeys = [];
  97176. vignetteStretchKeys.push({
  97177. frame: 0,
  97178. value: 0
  97179. });
  97180. vignetteStretchKeys.push({
  97181. frame: 5,
  97182. value: 10
  97183. });
  97184. vignetteStretchKeys.push({
  97185. frame: 11,
  97186. value: 0
  97187. });
  97188. animationPP2.setKeys(vignetteStretchKeys);
  97189. this._postProcessMove.animations.push(animationPP2);
  97190. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  97191. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  97192. this._webVRCamera.attachPostProcess(this._postProcessMove);
  97193. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  97194. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  97195. });
  97196. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  97197. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  97198. });
  97199. this._hideTeleportationTarget();
  97200. };
  97201. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  97202. if (normal) {
  97203. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  97204. if (angle < Math.PI / 2) {
  97205. normal.scaleInPlace(-1);
  97206. }
  97207. }
  97208. return normal;
  97209. };
  97210. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  97211. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  97212. return;
  97213. }
  97214. var ray = gazer._getForwardRay(this._rayLength);
  97215. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  97216. if (hit) {
  97217. // Populate the contrllers mesh that can be used for drag/drop
  97218. if (gazer._laserPointer) {
  97219. hit.originMesh = gazer._laserPointer.parent;
  97220. }
  97221. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  97222. }
  97223. gazer._currentHit = hit;
  97224. // Moving the gazeTracker on the mesh face targetted
  97225. if (hit && hit.pickedPoint) {
  97226. if (this._displayGaze) {
  97227. var multiplier = 1;
  97228. gazer._gazeTracker.isVisible = true;
  97229. if (gazer._isActionableMesh) {
  97230. multiplier = 3;
  97231. }
  97232. if (this.updateGazeTrackerScale) {
  97233. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  97234. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  97235. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  97236. }
  97237. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  97238. // To avoid z-fighting
  97239. var deltaFighting = 0.002;
  97240. if (pickNormal) {
  97241. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  97242. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  97243. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  97244. }
  97245. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  97246. if (gazer._gazeTracker.position.x < 0) {
  97247. gazer._gazeTracker.position.x += deltaFighting;
  97248. }
  97249. else {
  97250. gazer._gazeTracker.position.x -= deltaFighting;
  97251. }
  97252. if (gazer._gazeTracker.position.y < 0) {
  97253. gazer._gazeTracker.position.y += deltaFighting;
  97254. }
  97255. else {
  97256. gazer._gazeTracker.position.y -= deltaFighting;
  97257. }
  97258. if (gazer._gazeTracker.position.z < 0) {
  97259. gazer._gazeTracker.position.z += deltaFighting;
  97260. }
  97261. else {
  97262. gazer._gazeTracker.position.z -= deltaFighting;
  97263. }
  97264. }
  97265. // Changing the size of the laser pointer based on the distance from the targetted point
  97266. gazer._updatePointerDistance(hit.distance);
  97267. }
  97268. else {
  97269. gazer._updatePointerDistance();
  97270. gazer._gazeTracker.isVisible = false;
  97271. }
  97272. if (hit && hit.pickedMesh) {
  97273. // The object selected is the floor, we're in a teleportation scenario
  97274. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  97275. // Moving the teleportation area to this targetted point
  97276. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  97277. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  97278. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  97279. }
  97280. gazer._currentMeshSelected = null;
  97281. if (gazer._teleportationRequestInitiated) {
  97282. this._moveTeleportationSelectorTo(hit, gazer, ray);
  97283. }
  97284. return;
  97285. }
  97286. // If not, we're in a selection scenario
  97287. //this._teleportationAllowed = false;
  97288. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  97289. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  97290. this.onNewMeshPicked.notifyObservers(hit);
  97291. gazer._currentMeshSelected = hit.pickedMesh;
  97292. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  97293. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  97294. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  97295. gazer._isActionableMesh = true;
  97296. }
  97297. else {
  97298. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97299. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97300. gazer._isActionableMesh = false;
  97301. }
  97302. try {
  97303. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  97304. }
  97305. catch (err) {
  97306. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  97307. }
  97308. }
  97309. else {
  97310. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  97311. gazer._currentMeshSelected = null;
  97312. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97313. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97314. }
  97315. }
  97316. }
  97317. else {
  97318. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  97319. gazer._currentMeshSelected = null;
  97320. //this._teleportationAllowed = false;
  97321. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97322. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97323. }
  97324. };
  97325. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  97326. if (mesh) {
  97327. this.onSelectedMeshUnselected.notifyObservers(mesh);
  97328. }
  97329. };
  97330. /**
  97331. * Sets the color of the laser ray from the vr controllers.
  97332. * @param color new color for the ray.
  97333. */
  97334. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  97335. if (this._leftController) {
  97336. this._leftController._setLaserPointerColor(color);
  97337. }
  97338. if (this._rightController) {
  97339. this._rightController._setLaserPointerColor(color);
  97340. }
  97341. };
  97342. /**
  97343. * Sets the color of the ray from the vr headsets gaze.
  97344. * @param color new color for the ray.
  97345. */
  97346. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  97347. if (!this._cameraGazer._gazeTracker.material) {
  97348. return;
  97349. }
  97350. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  97351. if (this._leftController) {
  97352. this._leftController._gazeTracker.material.emissiveColor = color;
  97353. }
  97354. if (this._rightController) {
  97355. this._rightController._gazeTracker.material.emissiveColor = color;
  97356. }
  97357. };
  97358. /**
  97359. * Exits VR and disposes of the vr experience helper
  97360. */
  97361. VRExperienceHelper.prototype.dispose = function () {
  97362. if (this.isInVRMode) {
  97363. this.exitVR();
  97364. }
  97365. if (this._postProcessMove) {
  97366. this._postProcessMove.dispose();
  97367. }
  97368. if (this._webVRCamera) {
  97369. this._webVRCamera.dispose();
  97370. }
  97371. if (this._vrDeviceOrientationCamera) {
  97372. this._vrDeviceOrientationCamera.dispose();
  97373. }
  97374. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  97375. document.body.removeChild(this._btnVR);
  97376. }
  97377. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  97378. this._deviceOrientationCamera.dispose();
  97379. }
  97380. if (this._cameraGazer) {
  97381. this._cameraGazer.dispose();
  97382. }
  97383. if (this._leftController) {
  97384. this._leftController.dispose();
  97385. }
  97386. if (this._rightController) {
  97387. this._rightController.dispose();
  97388. }
  97389. if (this._teleportationTarget) {
  97390. this._teleportationTarget.dispose();
  97391. }
  97392. this._floorMeshesCollection = [];
  97393. document.removeEventListener("keydown", this._onKeyDown);
  97394. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  97395. window.removeEventListener("resize", this._onResize);
  97396. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  97397. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  97398. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  97399. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  97400. document.onmsfullscreenchange = null;
  97401. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  97402. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  97403. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  97404. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  97405. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  97406. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  97407. this._scene.unregisterBeforeRender(this.beforeRender);
  97408. };
  97409. /**
  97410. * Gets the name of the VRExperienceHelper class
  97411. * @returns "VRExperienceHelper"
  97412. */
  97413. VRExperienceHelper.prototype.getClassName = function () {
  97414. return "VRExperienceHelper";
  97415. };
  97416. return VRExperienceHelper;
  97417. }());
  97418. BABYLON.VRExperienceHelper = VRExperienceHelper;
  97419. })(BABYLON || (BABYLON = {}));
  97420. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  97421. // Mainly based on these 2 articles :
  97422. // 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
  97423. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  97424. var BABYLON;
  97425. (function (BABYLON) {
  97426. /**
  97427. * Defines the potential axis of a Joystick
  97428. */
  97429. var JoystickAxis;
  97430. (function (JoystickAxis) {
  97431. /** X axis */
  97432. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  97433. /** Y axis */
  97434. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  97435. /** Z axis */
  97436. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  97437. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  97438. /**
  97439. * Class used to define virtual joystick (used in touch mode)
  97440. */
  97441. var VirtualJoystick = /** @class */ (function () {
  97442. /**
  97443. * Creates a new virtual joystick
  97444. * @param leftJoystick defines that the joystick is for left hand (false by default)
  97445. */
  97446. function VirtualJoystick(leftJoystick) {
  97447. var _this = this;
  97448. if (leftJoystick) {
  97449. this._leftJoystick = true;
  97450. }
  97451. else {
  97452. this._leftJoystick = false;
  97453. }
  97454. VirtualJoystick._globalJoystickIndex++;
  97455. // By default left & right arrow keys are moving the X
  97456. // and up & down keys are moving the Y
  97457. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  97458. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  97459. this.reverseLeftRight = false;
  97460. this.reverseUpDown = false;
  97461. // collections of pointers
  97462. this._touches = new BABYLON.StringDictionary();
  97463. this.deltaPosition = BABYLON.Vector3.Zero();
  97464. this._joystickSensibility = 25;
  97465. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  97466. this._onResize = function (evt) {
  97467. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  97468. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  97469. if (VirtualJoystick.vjCanvas) {
  97470. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  97471. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  97472. }
  97473. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  97474. };
  97475. // injecting a canvas element on top of the canvas 3D game
  97476. if (!VirtualJoystick.vjCanvas) {
  97477. window.addEventListener("resize", this._onResize, false);
  97478. VirtualJoystick.vjCanvas = document.createElement("canvas");
  97479. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  97480. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  97481. VirtualJoystick.vjCanvas.width = window.innerWidth;
  97482. VirtualJoystick.vjCanvas.height = window.innerHeight;
  97483. VirtualJoystick.vjCanvas.style.width = "100%";
  97484. VirtualJoystick.vjCanvas.style.height = "100%";
  97485. VirtualJoystick.vjCanvas.style.position = "absolute";
  97486. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  97487. VirtualJoystick.vjCanvas.style.top = "0px";
  97488. VirtualJoystick.vjCanvas.style.left = "0px";
  97489. VirtualJoystick.vjCanvas.style.zIndex = "5";
  97490. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  97491. // Support for jQuery PEP polyfill
  97492. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  97493. var context = VirtualJoystick.vjCanvas.getContext('2d');
  97494. if (!context) {
  97495. throw new Error("Unable to create canvas for virtual joystick");
  97496. }
  97497. VirtualJoystick.vjCanvasContext = context;
  97498. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  97499. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  97500. document.body.appendChild(VirtualJoystick.vjCanvas);
  97501. }
  97502. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  97503. this.pressed = false;
  97504. // default joystick color
  97505. this._joystickColor = "cyan";
  97506. this._joystickPointerID = -1;
  97507. // current joystick position
  97508. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  97509. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  97510. // origin joystick position
  97511. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  97512. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  97513. this._onPointerDownHandlerRef = function (evt) {
  97514. _this._onPointerDown(evt);
  97515. };
  97516. this._onPointerMoveHandlerRef = function (evt) {
  97517. _this._onPointerMove(evt);
  97518. };
  97519. this._onPointerUpHandlerRef = function (evt) {
  97520. _this._onPointerUp(evt);
  97521. };
  97522. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  97523. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  97524. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  97525. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  97526. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  97527. evt.preventDefault(); // Disables system menu
  97528. }, false);
  97529. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  97530. }
  97531. /**
  97532. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  97533. * @param newJoystickSensibility defines the new sensibility
  97534. */
  97535. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  97536. this._joystickSensibility = newJoystickSensibility;
  97537. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  97538. };
  97539. VirtualJoystick.prototype._onPointerDown = function (e) {
  97540. var positionOnScreenCondition;
  97541. e.preventDefault();
  97542. if (this._leftJoystick === true) {
  97543. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  97544. }
  97545. else {
  97546. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  97547. }
  97548. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  97549. // First contact will be dedicated to the virtual joystick
  97550. this._joystickPointerID = e.pointerId;
  97551. this._joystickPointerStartPos.x = e.clientX;
  97552. this._joystickPointerStartPos.y = e.clientY;
  97553. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  97554. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  97555. this._deltaJoystickVector.x = 0;
  97556. this._deltaJoystickVector.y = 0;
  97557. this.pressed = true;
  97558. this._touches.add(e.pointerId.toString(), e);
  97559. }
  97560. else {
  97561. // You can only trigger the action buttons with a joystick declared
  97562. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  97563. this._action();
  97564. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  97565. }
  97566. }
  97567. };
  97568. VirtualJoystick.prototype._onPointerMove = function (e) {
  97569. // If the current pointer is the one associated to the joystick (first touch contact)
  97570. if (this._joystickPointerID == e.pointerId) {
  97571. this._joystickPointerPos.x = e.clientX;
  97572. this._joystickPointerPos.y = e.clientY;
  97573. this._deltaJoystickVector = this._joystickPointerPos.clone();
  97574. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  97575. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  97576. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  97577. switch (this._axisTargetedByLeftAndRight) {
  97578. case JoystickAxis.X:
  97579. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  97580. break;
  97581. case JoystickAxis.Y:
  97582. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  97583. break;
  97584. case JoystickAxis.Z:
  97585. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  97586. break;
  97587. }
  97588. var directionUpDown = this.reverseUpDown ? 1 : -1;
  97589. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  97590. switch (this._axisTargetedByUpAndDown) {
  97591. case JoystickAxis.X:
  97592. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  97593. break;
  97594. case JoystickAxis.Y:
  97595. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  97596. break;
  97597. case JoystickAxis.Z:
  97598. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  97599. break;
  97600. }
  97601. }
  97602. else {
  97603. var data = this._touches.get(e.pointerId.toString());
  97604. if (data) {
  97605. data.x = e.clientX;
  97606. data.y = e.clientY;
  97607. }
  97608. }
  97609. };
  97610. VirtualJoystick.prototype._onPointerUp = function (e) {
  97611. if (this._joystickPointerID == e.pointerId) {
  97612. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  97613. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  97614. this._joystickPointerID = -1;
  97615. this.pressed = false;
  97616. }
  97617. else {
  97618. var touch = this._touches.get(e.pointerId.toString());
  97619. if (touch) {
  97620. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  97621. }
  97622. }
  97623. this._deltaJoystickVector.x = 0;
  97624. this._deltaJoystickVector.y = 0;
  97625. this._touches.remove(e.pointerId.toString());
  97626. };
  97627. /**
  97628. * Change the color of the virtual joystick
  97629. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  97630. */
  97631. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  97632. this._joystickColor = newColor;
  97633. };
  97634. /**
  97635. * Defines a callback to call when the joystick is touched
  97636. * @param action defines the callback
  97637. */
  97638. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  97639. this._action = action;
  97640. };
  97641. /**
  97642. * Defines which axis you'd like to control for left & right
  97643. * @param axis defines the axis to use
  97644. */
  97645. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  97646. switch (axis) {
  97647. case JoystickAxis.X:
  97648. case JoystickAxis.Y:
  97649. case JoystickAxis.Z:
  97650. this._axisTargetedByLeftAndRight = axis;
  97651. break;
  97652. default:
  97653. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  97654. break;
  97655. }
  97656. };
  97657. /**
  97658. * Defines which axis you'd like to control for up & down
  97659. * @param axis defines the axis to use
  97660. */
  97661. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  97662. switch (axis) {
  97663. case JoystickAxis.X:
  97664. case JoystickAxis.Y:
  97665. case JoystickAxis.Z:
  97666. this._axisTargetedByUpAndDown = axis;
  97667. break;
  97668. default:
  97669. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  97670. break;
  97671. }
  97672. };
  97673. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  97674. var _this = this;
  97675. if (this.pressed) {
  97676. this._touches.forEach(function (key, touch) {
  97677. if (touch.pointerId === _this._joystickPointerID) {
  97678. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  97679. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  97680. VirtualJoystick.vjCanvasContext.beginPath();
  97681. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  97682. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  97683. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  97684. VirtualJoystick.vjCanvasContext.stroke();
  97685. VirtualJoystick.vjCanvasContext.closePath();
  97686. VirtualJoystick.vjCanvasContext.beginPath();
  97687. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  97688. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  97689. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  97690. VirtualJoystick.vjCanvasContext.stroke();
  97691. VirtualJoystick.vjCanvasContext.closePath();
  97692. VirtualJoystick.vjCanvasContext.beginPath();
  97693. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  97694. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  97695. VirtualJoystick.vjCanvasContext.stroke();
  97696. VirtualJoystick.vjCanvasContext.closePath();
  97697. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  97698. }
  97699. else {
  97700. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  97701. VirtualJoystick.vjCanvasContext.beginPath();
  97702. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  97703. VirtualJoystick.vjCanvasContext.beginPath();
  97704. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  97705. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  97706. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  97707. VirtualJoystick.vjCanvasContext.stroke();
  97708. VirtualJoystick.vjCanvasContext.closePath();
  97709. touch.prevX = touch.x;
  97710. touch.prevY = touch.y;
  97711. }
  97712. ;
  97713. });
  97714. }
  97715. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  97716. };
  97717. /**
  97718. * Release internal HTML canvas
  97719. */
  97720. VirtualJoystick.prototype.releaseCanvas = function () {
  97721. if (VirtualJoystick.vjCanvas) {
  97722. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  97723. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  97724. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  97725. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  97726. window.removeEventListener("resize", this._onResize);
  97727. document.body.removeChild(VirtualJoystick.vjCanvas);
  97728. VirtualJoystick.vjCanvas = null;
  97729. }
  97730. };
  97731. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  97732. VirtualJoystick._globalJoystickIndex = 0;
  97733. return VirtualJoystick;
  97734. }());
  97735. BABYLON.VirtualJoystick = VirtualJoystick;
  97736. })(BABYLON || (BABYLON = {}));
  97737. //# sourceMappingURL=babylon.virtualJoystick.js.map
  97738. var BABYLON;
  97739. (function (BABYLON) {
  97740. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  97741. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  97742. });
  97743. // We're mainly based on the logic defined into the FreeCamera code
  97744. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  97745. __extends(VirtualJoysticksCamera, _super);
  97746. function VirtualJoysticksCamera(name, position, scene) {
  97747. var _this = _super.call(this, name, position, scene) || this;
  97748. _this.inputs.addVirtualJoystick();
  97749. return _this;
  97750. }
  97751. VirtualJoysticksCamera.prototype.getClassName = function () {
  97752. return "VirtualJoysticksCamera";
  97753. };
  97754. return VirtualJoysticksCamera;
  97755. }(BABYLON.FreeCamera));
  97756. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  97757. })(BABYLON || (BABYLON = {}));
  97758. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  97759. var BABYLON;
  97760. (function (BABYLON) {
  97761. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  97762. function FreeCameraVirtualJoystickInput() {
  97763. }
  97764. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  97765. return this._leftjoystick;
  97766. };
  97767. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  97768. return this._rightjoystick;
  97769. };
  97770. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  97771. if (this._leftjoystick) {
  97772. var camera = this.camera;
  97773. var speed = camera._computeLocalCameraSpeed() * 50;
  97774. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  97775. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  97776. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  97777. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  97778. if (!this._leftjoystick.pressed) {
  97779. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  97780. }
  97781. if (!this._rightjoystick.pressed) {
  97782. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  97783. }
  97784. }
  97785. };
  97786. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  97787. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  97788. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  97789. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  97790. this._leftjoystick.setJoystickSensibility(0.15);
  97791. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  97792. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  97793. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  97794. this._rightjoystick.reverseUpDown = true;
  97795. this._rightjoystick.setJoystickSensibility(0.05);
  97796. this._rightjoystick.setJoystickColor("yellow");
  97797. };
  97798. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  97799. this._leftjoystick.releaseCanvas();
  97800. this._rightjoystick.releaseCanvas();
  97801. };
  97802. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  97803. return "FreeCameraVirtualJoystickInput";
  97804. };
  97805. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  97806. return "virtualJoystick";
  97807. };
  97808. return FreeCameraVirtualJoystickInput;
  97809. }());
  97810. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  97811. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  97812. })(BABYLON || (BABYLON = {}));
  97813. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  97814. var BABYLON;
  97815. (function (BABYLON) {
  97816. var SimplificationSettings = /** @class */ (function () {
  97817. function SimplificationSettings(quality, distance, optimizeMesh) {
  97818. this.quality = quality;
  97819. this.distance = distance;
  97820. this.optimizeMesh = optimizeMesh;
  97821. }
  97822. return SimplificationSettings;
  97823. }());
  97824. BABYLON.SimplificationSettings = SimplificationSettings;
  97825. var SimplificationQueue = /** @class */ (function () {
  97826. function SimplificationQueue() {
  97827. this.running = false;
  97828. this._simplificationArray = [];
  97829. }
  97830. SimplificationQueue.prototype.addTask = function (task) {
  97831. this._simplificationArray.push(task);
  97832. };
  97833. SimplificationQueue.prototype.executeNext = function () {
  97834. var task = this._simplificationArray.pop();
  97835. if (task) {
  97836. this.running = true;
  97837. this.runSimplification(task);
  97838. }
  97839. else {
  97840. this.running = false;
  97841. }
  97842. };
  97843. SimplificationQueue.prototype.runSimplification = function (task) {
  97844. var _this = this;
  97845. if (task.parallelProcessing) {
  97846. //parallel simplifier
  97847. task.settings.forEach(function (setting) {
  97848. var simplifier = _this.getSimplifier(task);
  97849. simplifier.simplify(setting, function (newMesh) {
  97850. task.mesh.addLODLevel(setting.distance, newMesh);
  97851. newMesh.isVisible = true;
  97852. //check if it is the last
  97853. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  97854. //all done, run the success callback.
  97855. task.successCallback();
  97856. }
  97857. _this.executeNext();
  97858. });
  97859. });
  97860. }
  97861. else {
  97862. //single simplifier.
  97863. var simplifier = this.getSimplifier(task);
  97864. var runDecimation = function (setting, callback) {
  97865. simplifier.simplify(setting, function (newMesh) {
  97866. task.mesh.addLODLevel(setting.distance, newMesh);
  97867. newMesh.isVisible = true;
  97868. //run the next quality level
  97869. callback();
  97870. });
  97871. };
  97872. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  97873. runDecimation(task.settings[loop.index], function () {
  97874. loop.executeNext();
  97875. });
  97876. }, function () {
  97877. //execution ended, run the success callback.
  97878. if (task.successCallback) {
  97879. task.successCallback();
  97880. }
  97881. _this.executeNext();
  97882. });
  97883. }
  97884. };
  97885. SimplificationQueue.prototype.getSimplifier = function (task) {
  97886. switch (task.simplificationType) {
  97887. case SimplificationType.QUADRATIC:
  97888. default:
  97889. return new QuadraticErrorSimplification(task.mesh);
  97890. }
  97891. };
  97892. return SimplificationQueue;
  97893. }());
  97894. BABYLON.SimplificationQueue = SimplificationQueue;
  97895. /**
  97896. * The implemented types of simplification
  97897. * At the moment only Quadratic Error Decimation is implemented
  97898. */
  97899. var SimplificationType;
  97900. (function (SimplificationType) {
  97901. /** Quadratic error decimation */
  97902. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  97903. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  97904. var DecimationTriangle = /** @class */ (function () {
  97905. function DecimationTriangle(vertices) {
  97906. this.vertices = vertices;
  97907. this.error = new Array(4);
  97908. this.deleted = false;
  97909. this.isDirty = false;
  97910. this.deletePending = false;
  97911. this.borderFactor = 0;
  97912. }
  97913. return DecimationTriangle;
  97914. }());
  97915. BABYLON.DecimationTriangle = DecimationTriangle;
  97916. var DecimationVertex = /** @class */ (function () {
  97917. function DecimationVertex(position, id) {
  97918. this.position = position;
  97919. this.id = id;
  97920. this.isBorder = true;
  97921. this.q = new QuadraticMatrix();
  97922. this.triangleCount = 0;
  97923. this.triangleStart = 0;
  97924. this.originalOffsets = [];
  97925. }
  97926. DecimationVertex.prototype.updatePosition = function (newPosition) {
  97927. this.position.copyFrom(newPosition);
  97928. };
  97929. return DecimationVertex;
  97930. }());
  97931. BABYLON.DecimationVertex = DecimationVertex;
  97932. var QuadraticMatrix = /** @class */ (function () {
  97933. function QuadraticMatrix(data) {
  97934. this.data = new Array(10);
  97935. for (var i = 0; i < 10; ++i) {
  97936. if (data && data[i]) {
  97937. this.data[i] = data[i];
  97938. }
  97939. else {
  97940. this.data[i] = 0;
  97941. }
  97942. }
  97943. }
  97944. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  97945. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  97946. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  97947. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  97948. return det;
  97949. };
  97950. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  97951. for (var i = 0; i < 10; ++i) {
  97952. this.data[i] += matrix.data[i];
  97953. }
  97954. };
  97955. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  97956. for (var i = 0; i < 10; ++i) {
  97957. this.data[i] += data[i];
  97958. }
  97959. };
  97960. QuadraticMatrix.prototype.add = function (matrix) {
  97961. var m = new QuadraticMatrix();
  97962. for (var i = 0; i < 10; ++i) {
  97963. m.data[i] = this.data[i] + matrix.data[i];
  97964. }
  97965. return m;
  97966. };
  97967. QuadraticMatrix.FromData = function (a, b, c, d) {
  97968. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  97969. };
  97970. //returning an array to avoid garbage collection
  97971. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  97972. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  97973. };
  97974. return QuadraticMatrix;
  97975. }());
  97976. BABYLON.QuadraticMatrix = QuadraticMatrix;
  97977. var Reference = /** @class */ (function () {
  97978. function Reference(vertexId, triangleId) {
  97979. this.vertexId = vertexId;
  97980. this.triangleId = triangleId;
  97981. }
  97982. return Reference;
  97983. }());
  97984. BABYLON.Reference = Reference;
  97985. /**
  97986. * An implementation of the Quadratic Error simplification algorithm.
  97987. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  97988. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  97989. * @author RaananW
  97990. */
  97991. var QuadraticErrorSimplification = /** @class */ (function () {
  97992. function QuadraticErrorSimplification(_mesh) {
  97993. this._mesh = _mesh;
  97994. this.syncIterations = 5000;
  97995. this.aggressiveness = 7;
  97996. this.decimationIterations = 100;
  97997. this.boundingBoxEpsilon = BABYLON.Epsilon;
  97998. }
  97999. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  98000. var _this = this;
  98001. this.initDecimatedMesh();
  98002. //iterating through the submeshes array, one after the other.
  98003. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  98004. _this.initWithMesh(loop.index, function () {
  98005. _this.runDecimation(settings, loop.index, function () {
  98006. loop.executeNext();
  98007. });
  98008. }, settings.optimizeMesh);
  98009. }, function () {
  98010. setTimeout(function () {
  98011. successCallback(_this._reconstructedMesh);
  98012. }, 0);
  98013. });
  98014. };
  98015. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  98016. var _this = this;
  98017. var targetCount = ~~(this.triangles.length * settings.quality);
  98018. var deletedTriangles = 0;
  98019. var triangleCount = this.triangles.length;
  98020. var iterationFunction = function (iteration, callback) {
  98021. setTimeout(function () {
  98022. if (iteration % 5 === 0) {
  98023. _this.updateMesh(iteration === 0);
  98024. }
  98025. for (var i = 0; i < _this.triangles.length; ++i) {
  98026. _this.triangles[i].isDirty = false;
  98027. }
  98028. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  98029. var trianglesIterator = function (i) {
  98030. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  98031. var t = _this.triangles[tIdx];
  98032. if (!t)
  98033. return;
  98034. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  98035. return;
  98036. }
  98037. for (var j = 0; j < 3; ++j) {
  98038. if (t.error[j] < threshold) {
  98039. var deleted0 = [];
  98040. var deleted1 = [];
  98041. var v0 = t.vertices[j];
  98042. var v1 = t.vertices[(j + 1) % 3];
  98043. if (v0.isBorder || v1.isBorder)
  98044. continue;
  98045. var p = BABYLON.Vector3.Zero();
  98046. var n = BABYLON.Vector3.Zero();
  98047. var uv = BABYLON.Vector2.Zero();
  98048. var color = new BABYLON.Color4(0, 0, 0, 1);
  98049. _this.calculateError(v0, v1, p, n, uv, color);
  98050. var delTr = new Array();
  98051. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  98052. continue;
  98053. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  98054. continue;
  98055. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  98056. continue;
  98057. var uniqueArray = new Array();
  98058. delTr.forEach(function (deletedT) {
  98059. if (uniqueArray.indexOf(deletedT) === -1) {
  98060. deletedT.deletePending = true;
  98061. uniqueArray.push(deletedT);
  98062. }
  98063. });
  98064. if (uniqueArray.length % 2 !== 0) {
  98065. continue;
  98066. }
  98067. v0.q = v1.q.add(v0.q);
  98068. v0.updatePosition(p);
  98069. var tStart = _this.references.length;
  98070. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  98071. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  98072. var tCount = _this.references.length - tStart;
  98073. if (tCount <= v0.triangleCount) {
  98074. if (tCount) {
  98075. for (var c = 0; c < tCount; c++) {
  98076. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  98077. }
  98078. }
  98079. }
  98080. else {
  98081. v0.triangleStart = tStart;
  98082. }
  98083. v0.triangleCount = tCount;
  98084. break;
  98085. }
  98086. }
  98087. };
  98088. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  98089. }, 0);
  98090. };
  98091. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  98092. if (triangleCount - deletedTriangles <= targetCount)
  98093. loop.breakLoop();
  98094. else {
  98095. iterationFunction(loop.index, function () {
  98096. loop.executeNext();
  98097. });
  98098. }
  98099. }, function () {
  98100. setTimeout(function () {
  98101. //reconstruct this part of the mesh
  98102. _this.reconstructMesh(submeshIndex);
  98103. successCallback();
  98104. }, 0);
  98105. });
  98106. };
  98107. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  98108. var _this = this;
  98109. this.vertices = [];
  98110. this.triangles = [];
  98111. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  98112. var indices = this._mesh.getIndices();
  98113. var submesh = this._mesh.subMeshes[submeshIndex];
  98114. var findInVertices = function (positionToSearch) {
  98115. if (optimizeMesh) {
  98116. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  98117. if (_this.vertices[ii].position.equals(positionToSearch)) {
  98118. return _this.vertices[ii];
  98119. }
  98120. }
  98121. }
  98122. return null;
  98123. };
  98124. var vertexReferences = [];
  98125. var vertexInit = function (i) {
  98126. if (!positionData) {
  98127. return;
  98128. }
  98129. var offset = i + submesh.verticesStart;
  98130. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  98131. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  98132. vertex.originalOffsets.push(offset);
  98133. if (vertex.id === _this.vertices.length) {
  98134. _this.vertices.push(vertex);
  98135. }
  98136. vertexReferences.push(vertex.id);
  98137. };
  98138. //var totalVertices = mesh.getTotalVertices();
  98139. var totalVertices = submesh.verticesCount;
  98140. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  98141. var indicesInit = function (i) {
  98142. if (!indices) {
  98143. return;
  98144. }
  98145. var offset = (submesh.indexStart / 3) + i;
  98146. var pos = (offset * 3);
  98147. var i0 = indices[pos + 0];
  98148. var i1 = indices[pos + 1];
  98149. var i2 = indices[pos + 2];
  98150. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  98151. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  98152. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  98153. var triangle = new DecimationTriangle([v0, v1, v2]);
  98154. triangle.originalOffset = pos;
  98155. _this.triangles.push(triangle);
  98156. };
  98157. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  98158. _this.init(callback);
  98159. });
  98160. });
  98161. };
  98162. QuadraticErrorSimplification.prototype.init = function (callback) {
  98163. var _this = this;
  98164. var triangleInit1 = function (i) {
  98165. var t = _this.triangles[i];
  98166. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  98167. for (var j = 0; j < 3; j++) {
  98168. 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))));
  98169. }
  98170. };
  98171. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  98172. var triangleInit2 = function (i) {
  98173. var t = _this.triangles[i];
  98174. for (var j = 0; j < 3; ++j) {
  98175. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  98176. }
  98177. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  98178. };
  98179. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  98180. callback();
  98181. });
  98182. });
  98183. };
  98184. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  98185. var newTriangles = [];
  98186. var i;
  98187. for (i = 0; i < this.vertices.length; ++i) {
  98188. this.vertices[i].triangleCount = 0;
  98189. }
  98190. var t;
  98191. var j;
  98192. for (i = 0; i < this.triangles.length; ++i) {
  98193. if (!this.triangles[i].deleted) {
  98194. t = this.triangles[i];
  98195. for (j = 0; j < 3; ++j) {
  98196. t.vertices[j].triangleCount = 1;
  98197. }
  98198. newTriangles.push(t);
  98199. }
  98200. }
  98201. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  98202. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  98203. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  98204. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  98205. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  98206. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  98207. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  98208. var vertexCount = 0;
  98209. for (i = 0; i < this.vertices.length; ++i) {
  98210. var vertex = this.vertices[i];
  98211. vertex.id = vertexCount;
  98212. if (vertex.triangleCount) {
  98213. vertex.originalOffsets.forEach(function (originalOffset) {
  98214. if (!normalData) {
  98215. return;
  98216. }
  98217. newPositionData.push(vertex.position.x);
  98218. newPositionData.push(vertex.position.y);
  98219. newPositionData.push(vertex.position.z);
  98220. newNormalData.push(normalData[originalOffset * 3]);
  98221. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  98222. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  98223. if (uvs && uvs.length) {
  98224. newUVsData.push(uvs[(originalOffset * 2)]);
  98225. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  98226. }
  98227. else if (colorsData && colorsData.length) {
  98228. newColorsData.push(colorsData[(originalOffset * 4)]);
  98229. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  98230. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  98231. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  98232. }
  98233. ++vertexCount;
  98234. });
  98235. }
  98236. }
  98237. var startingIndex = this._reconstructedMesh.getTotalIndices();
  98238. var startingVertex = this._reconstructedMesh.getTotalVertices();
  98239. var submeshesArray = this._reconstructedMesh.subMeshes;
  98240. this._reconstructedMesh.subMeshes = [];
  98241. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  98242. var originalIndices = this._mesh.getIndices();
  98243. for (i = 0; i < newTriangles.length; ++i) {
  98244. t = newTriangles[i]; //now get the new referencing point for each vertex
  98245. [0, 1, 2].forEach(function (idx) {
  98246. var id = originalIndices[t.originalOffset + idx];
  98247. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  98248. if (offset < 0)
  98249. offset = 0;
  98250. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  98251. });
  98252. }
  98253. //overwriting the old vertex buffers and indices.
  98254. this._reconstructedMesh.setIndices(newIndicesArray);
  98255. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  98256. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  98257. if (newUVsData.length > 0)
  98258. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  98259. if (newColorsData.length > 0)
  98260. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  98261. //create submesh
  98262. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  98263. if (submeshIndex > 0) {
  98264. this._reconstructedMesh.subMeshes = [];
  98265. submeshesArray.forEach(function (submesh) {
  98266. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  98267. });
  98268. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  98269. }
  98270. };
  98271. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  98272. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  98273. this._reconstructedMesh.material = this._mesh.material;
  98274. this._reconstructedMesh.parent = this._mesh.parent;
  98275. this._reconstructedMesh.isVisible = false;
  98276. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  98277. };
  98278. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  98279. for (var i = 0; i < vertex1.triangleCount; ++i) {
  98280. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  98281. if (t.deleted)
  98282. continue;
  98283. var s = this.references[vertex1.triangleStart + i].vertexId;
  98284. var v1 = t.vertices[(s + 1) % 3];
  98285. var v2 = t.vertices[(s + 2) % 3];
  98286. if ((v1 === vertex2 || v2 === vertex2)) {
  98287. deletedArray[i] = true;
  98288. delTr.push(t);
  98289. continue;
  98290. }
  98291. var d1 = v1.position.subtract(point);
  98292. d1 = d1.normalize();
  98293. var d2 = v2.position.subtract(point);
  98294. d2 = d2.normalize();
  98295. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  98296. return true;
  98297. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  98298. deletedArray[i] = false;
  98299. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  98300. return true;
  98301. }
  98302. return false;
  98303. };
  98304. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  98305. var newDeleted = deletedTriangles;
  98306. for (var i = 0; i < vertex.triangleCount; ++i) {
  98307. var ref = this.references[vertex.triangleStart + i];
  98308. var t = this.triangles[ref.triangleId];
  98309. if (t.deleted)
  98310. continue;
  98311. if (deletedArray[i] && t.deletePending) {
  98312. t.deleted = true;
  98313. newDeleted++;
  98314. continue;
  98315. }
  98316. t.vertices[ref.vertexId] = origVertex;
  98317. t.isDirty = true;
  98318. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  98319. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  98320. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  98321. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  98322. this.references.push(ref);
  98323. }
  98324. return newDeleted;
  98325. };
  98326. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  98327. for (var i = 0; i < this.vertices.length; ++i) {
  98328. var vCount = [];
  98329. var vId = [];
  98330. var v = this.vertices[i];
  98331. var j;
  98332. for (j = 0; j < v.triangleCount; ++j) {
  98333. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  98334. for (var ii = 0; ii < 3; ii++) {
  98335. var ofs = 0;
  98336. var vv = triangle.vertices[ii];
  98337. while (ofs < vCount.length) {
  98338. if (vId[ofs] === vv.id)
  98339. break;
  98340. ++ofs;
  98341. }
  98342. if (ofs === vCount.length) {
  98343. vCount.push(1);
  98344. vId.push(vv.id);
  98345. }
  98346. else {
  98347. vCount[ofs]++;
  98348. }
  98349. }
  98350. }
  98351. for (j = 0; j < vCount.length; ++j) {
  98352. if (vCount[j] === 1) {
  98353. this.vertices[vId[j]].isBorder = true;
  98354. }
  98355. else {
  98356. this.vertices[vId[j]].isBorder = false;
  98357. }
  98358. }
  98359. }
  98360. };
  98361. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  98362. if (identifyBorders === void 0) { identifyBorders = false; }
  98363. var i;
  98364. if (!identifyBorders) {
  98365. var newTrianglesVector = [];
  98366. for (i = 0; i < this.triangles.length; ++i) {
  98367. if (!this.triangles[i].deleted) {
  98368. newTrianglesVector.push(this.triangles[i]);
  98369. }
  98370. }
  98371. this.triangles = newTrianglesVector;
  98372. }
  98373. for (i = 0; i < this.vertices.length; ++i) {
  98374. this.vertices[i].triangleCount = 0;
  98375. this.vertices[i].triangleStart = 0;
  98376. }
  98377. var t;
  98378. var j;
  98379. var v;
  98380. for (i = 0; i < this.triangles.length; ++i) {
  98381. t = this.triangles[i];
  98382. for (j = 0; j < 3; ++j) {
  98383. v = t.vertices[j];
  98384. v.triangleCount++;
  98385. }
  98386. }
  98387. var tStart = 0;
  98388. for (i = 0; i < this.vertices.length; ++i) {
  98389. this.vertices[i].triangleStart = tStart;
  98390. tStart += this.vertices[i].triangleCount;
  98391. this.vertices[i].triangleCount = 0;
  98392. }
  98393. var newReferences = new Array(this.triangles.length * 3);
  98394. for (i = 0; i < this.triangles.length; ++i) {
  98395. t = this.triangles[i];
  98396. for (j = 0; j < 3; ++j) {
  98397. v = t.vertices[j];
  98398. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  98399. v.triangleCount++;
  98400. }
  98401. }
  98402. this.references = newReferences;
  98403. if (identifyBorders) {
  98404. this.identifyBorder();
  98405. }
  98406. };
  98407. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  98408. var x = point.x;
  98409. var y = point.y;
  98410. var z = point.z;
  98411. 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
  98412. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  98413. };
  98414. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  98415. var q = vertex1.q.add(vertex2.q);
  98416. var border = vertex1.isBorder && vertex2.isBorder;
  98417. var error = 0;
  98418. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  98419. if (qDet !== 0 && !border) {
  98420. if (!pointResult) {
  98421. pointResult = BABYLON.Vector3.Zero();
  98422. }
  98423. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  98424. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  98425. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  98426. error = this.vertexError(q, pointResult);
  98427. }
  98428. else {
  98429. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  98430. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  98431. var error1 = this.vertexError(q, vertex1.position);
  98432. var error2 = this.vertexError(q, vertex2.position);
  98433. var error3 = this.vertexError(q, p3);
  98434. error = Math.min(error1, error2, error3);
  98435. if (error === error1) {
  98436. if (pointResult) {
  98437. pointResult.copyFrom(vertex1.position);
  98438. }
  98439. }
  98440. else if (error === error2) {
  98441. if (pointResult) {
  98442. pointResult.copyFrom(vertex2.position);
  98443. }
  98444. }
  98445. else {
  98446. if (pointResult) {
  98447. pointResult.copyFrom(p3);
  98448. }
  98449. }
  98450. }
  98451. return error;
  98452. };
  98453. return QuadraticErrorSimplification;
  98454. }());
  98455. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  98456. })(BABYLON || (BABYLON = {}));
  98457. //# sourceMappingURL=babylon.meshSimplification.js.map
  98458. var BABYLON;
  98459. (function (BABYLON) {
  98460. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  98461. get: function () {
  98462. if (!this._simplificationQueue) {
  98463. this._simplificationQueue = new BABYLON.SimplificationQueue();
  98464. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  98465. if (!component) {
  98466. component = new SimplicationQueueSceneComponent(this);
  98467. this._addComponent(component);
  98468. }
  98469. }
  98470. return this._simplificationQueue;
  98471. },
  98472. set: function (value) {
  98473. this._simplificationQueue = value;
  98474. },
  98475. enumerable: true,
  98476. configurable: true
  98477. });
  98478. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  98479. if (parallelProcessing === void 0) { parallelProcessing = true; }
  98480. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  98481. this.getScene().simplificationQueue.addTask({
  98482. settings: settings,
  98483. parallelProcessing: parallelProcessing,
  98484. mesh: this,
  98485. simplificationType: simplificationType,
  98486. successCallback: successCallback
  98487. });
  98488. return this;
  98489. };
  98490. /**
  98491. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  98492. * created in a scene
  98493. */
  98494. var SimplicationQueueSceneComponent = /** @class */ (function () {
  98495. /**
  98496. * Creates a new instance of the component for the given scene
  98497. * @param scene Defines the scene to register the component in
  98498. */
  98499. function SimplicationQueueSceneComponent(scene) {
  98500. /**
  98501. * The component name helpfull to identify the component in the list of scene components.
  98502. */
  98503. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  98504. this.scene = scene;
  98505. }
  98506. /**
  98507. * Registers the component in a given scene
  98508. */
  98509. SimplicationQueueSceneComponent.prototype.register = function () {
  98510. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  98511. };
  98512. /**
  98513. * Rebuilds the elements related to this component in case of
  98514. * context lost for instance.
  98515. */
  98516. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  98517. // Nothing to do for this component
  98518. };
  98519. /**
  98520. * Disposes the component and the associated ressources
  98521. */
  98522. SimplicationQueueSceneComponent.prototype.dispose = function () {
  98523. // Nothing to do for this component
  98524. };
  98525. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  98526. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  98527. this.scene._simplificationQueue.executeNext();
  98528. }
  98529. };
  98530. return SimplicationQueueSceneComponent;
  98531. }());
  98532. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  98533. })(BABYLON || (BABYLON = {}));
  98534. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  98535. var BABYLON;
  98536. (function (BABYLON) {
  98537. var MeshLODLevel = /** @class */ (function () {
  98538. function MeshLODLevel(distance, mesh) {
  98539. this.distance = distance;
  98540. this.mesh = mesh;
  98541. }
  98542. return MeshLODLevel;
  98543. }());
  98544. BABYLON.MeshLODLevel = MeshLODLevel;
  98545. })(BABYLON || (BABYLON = {}));
  98546. //# sourceMappingURL=babylon.meshLODLevel.js.map
  98547. var BABYLON;
  98548. (function (BABYLON) {
  98549. /**
  98550. * Defines the root class used to create scene optimization to use with SceneOptimizer
  98551. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98552. */
  98553. var SceneOptimization = /** @class */ (function () {
  98554. /**
  98555. * Creates the SceneOptimization object
  98556. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  98557. * @param desc defines the description associated with the optimization
  98558. */
  98559. function SceneOptimization(
  98560. /**
  98561. * Defines the priority of this optimization (0 by default which means first in the list)
  98562. */
  98563. priority) {
  98564. if (priority === void 0) { priority = 0; }
  98565. this.priority = priority;
  98566. }
  98567. /**
  98568. * Gets a string describing the action executed by the current optimization
  98569. * @returns description string
  98570. */
  98571. SceneOptimization.prototype.getDescription = function () {
  98572. return "";
  98573. };
  98574. /**
  98575. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98576. * @param scene defines the current scene where to apply this optimization
  98577. * @param optimizer defines the current optimizer
  98578. * @returns true if everything that can be done was applied
  98579. */
  98580. SceneOptimization.prototype.apply = function (scene, optimizer) {
  98581. return true;
  98582. };
  98583. ;
  98584. return SceneOptimization;
  98585. }());
  98586. BABYLON.SceneOptimization = SceneOptimization;
  98587. /**
  98588. * Defines an optimization used to reduce the size of render target textures
  98589. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98590. */
  98591. var TextureOptimization = /** @class */ (function (_super) {
  98592. __extends(TextureOptimization, _super);
  98593. /**
  98594. * Creates the TextureOptimization object
  98595. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  98596. * @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
  98597. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  98598. */
  98599. function TextureOptimization(
  98600. /**
  98601. * Defines the priority of this optimization (0 by default which means first in the list)
  98602. */
  98603. priority,
  98604. /**
  98605. * 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
  98606. */
  98607. maximumSize,
  98608. /**
  98609. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  98610. */
  98611. step) {
  98612. if (priority === void 0) { priority = 0; }
  98613. if (maximumSize === void 0) { maximumSize = 1024; }
  98614. if (step === void 0) { step = 0.5; }
  98615. var _this = _super.call(this, priority) || this;
  98616. _this.priority = priority;
  98617. _this.maximumSize = maximumSize;
  98618. _this.step = step;
  98619. return _this;
  98620. }
  98621. /**
  98622. * Gets a string describing the action executed by the current optimization
  98623. * @returns description string
  98624. */
  98625. TextureOptimization.prototype.getDescription = function () {
  98626. return "Reducing render target texture size to " + this.maximumSize;
  98627. };
  98628. /**
  98629. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98630. * @param scene defines the current scene where to apply this optimization
  98631. * @param optimizer defines the current optimizer
  98632. * @returns true if everything that can be done was applied
  98633. */
  98634. TextureOptimization.prototype.apply = function (scene, optimizer) {
  98635. var allDone = true;
  98636. for (var index = 0; index < scene.textures.length; index++) {
  98637. var texture = scene.textures[index];
  98638. if (!texture.canRescale || texture.getContext) {
  98639. continue;
  98640. }
  98641. var currentSize = texture.getSize();
  98642. var maxDimension = Math.max(currentSize.width, currentSize.height);
  98643. if (maxDimension > this.maximumSize) {
  98644. texture.scale(this.step);
  98645. allDone = false;
  98646. }
  98647. }
  98648. return allDone;
  98649. };
  98650. return TextureOptimization;
  98651. }(SceneOptimization));
  98652. BABYLON.TextureOptimization = TextureOptimization;
  98653. /**
  98654. * Defines an optimization used to increase or decrease the rendering resolution
  98655. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98656. */
  98657. var HardwareScalingOptimization = /** @class */ (function (_super) {
  98658. __extends(HardwareScalingOptimization, _super);
  98659. /**
  98660. * Creates the HardwareScalingOptimization object
  98661. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  98662. * @param maximumScale defines the maximum scale to use (2 by default)
  98663. * @param step defines the step to use between two passes (0.5 by default)
  98664. */
  98665. function HardwareScalingOptimization(
  98666. /**
  98667. * Defines the priority of this optimization (0 by default which means first in the list)
  98668. */
  98669. priority,
  98670. /**
  98671. * Defines the maximum scale to use (2 by default)
  98672. */
  98673. maximumScale,
  98674. /**
  98675. * Defines the step to use between two passes (0.5 by default)
  98676. */
  98677. step) {
  98678. if (priority === void 0) { priority = 0; }
  98679. if (maximumScale === void 0) { maximumScale = 2; }
  98680. if (step === void 0) { step = 0.25; }
  98681. var _this = _super.call(this, priority) || this;
  98682. _this.priority = priority;
  98683. _this.maximumScale = maximumScale;
  98684. _this.step = step;
  98685. _this._currentScale = -1;
  98686. _this._directionOffset = 1;
  98687. return _this;
  98688. }
  98689. /**
  98690. * Gets a string describing the action executed by the current optimization
  98691. * @return description string
  98692. */
  98693. HardwareScalingOptimization.prototype.getDescription = function () {
  98694. return "Setting hardware scaling level to " + this._currentScale;
  98695. };
  98696. /**
  98697. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98698. * @param scene defines the current scene where to apply this optimization
  98699. * @param optimizer defines the current optimizer
  98700. * @returns true if everything that can be done was applied
  98701. */
  98702. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  98703. if (this._currentScale === -1) {
  98704. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  98705. if (this._currentScale > this.maximumScale) {
  98706. this._directionOffset = -1;
  98707. }
  98708. }
  98709. this._currentScale += this._directionOffset * this.step;
  98710. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  98711. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  98712. };
  98713. ;
  98714. return HardwareScalingOptimization;
  98715. }(SceneOptimization));
  98716. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  98717. /**
  98718. * Defines an optimization used to remove shadows
  98719. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98720. */
  98721. var ShadowsOptimization = /** @class */ (function (_super) {
  98722. __extends(ShadowsOptimization, _super);
  98723. function ShadowsOptimization() {
  98724. return _super !== null && _super.apply(this, arguments) || this;
  98725. }
  98726. /**
  98727. * Gets a string describing the action executed by the current optimization
  98728. * @return description string
  98729. */
  98730. ShadowsOptimization.prototype.getDescription = function () {
  98731. return "Turning shadows on/off";
  98732. };
  98733. /**
  98734. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98735. * @param scene defines the current scene where to apply this optimization
  98736. * @param optimizer defines the current optimizer
  98737. * @returns true if everything that can be done was applied
  98738. */
  98739. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  98740. scene.shadowsEnabled = optimizer.isInImprovementMode;
  98741. return true;
  98742. };
  98743. ;
  98744. return ShadowsOptimization;
  98745. }(SceneOptimization));
  98746. BABYLON.ShadowsOptimization = ShadowsOptimization;
  98747. /**
  98748. * Defines an optimization used to turn post-processes off
  98749. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98750. */
  98751. var PostProcessesOptimization = /** @class */ (function (_super) {
  98752. __extends(PostProcessesOptimization, _super);
  98753. function PostProcessesOptimization() {
  98754. return _super !== null && _super.apply(this, arguments) || this;
  98755. }
  98756. /**
  98757. * Gets a string describing the action executed by the current optimization
  98758. * @return description string
  98759. */
  98760. PostProcessesOptimization.prototype.getDescription = function () {
  98761. return "Turning post-processes on/off";
  98762. };
  98763. /**
  98764. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98765. * @param scene defines the current scene where to apply this optimization
  98766. * @param optimizer defines the current optimizer
  98767. * @returns true if everything that can be done was applied
  98768. */
  98769. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  98770. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  98771. return true;
  98772. };
  98773. ;
  98774. return PostProcessesOptimization;
  98775. }(SceneOptimization));
  98776. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  98777. /**
  98778. * Defines an optimization used to turn lens flares off
  98779. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98780. */
  98781. var LensFlaresOptimization = /** @class */ (function (_super) {
  98782. __extends(LensFlaresOptimization, _super);
  98783. function LensFlaresOptimization() {
  98784. return _super !== null && _super.apply(this, arguments) || this;
  98785. }
  98786. /**
  98787. * Gets a string describing the action executed by the current optimization
  98788. * @return description string
  98789. */
  98790. LensFlaresOptimization.prototype.getDescription = function () {
  98791. return "Turning lens flares on/off";
  98792. };
  98793. /**
  98794. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98795. * @param scene defines the current scene where to apply this optimization
  98796. * @param optimizer defines the current optimizer
  98797. * @returns true if everything that can be done was applied
  98798. */
  98799. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  98800. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  98801. return true;
  98802. };
  98803. ;
  98804. return LensFlaresOptimization;
  98805. }(SceneOptimization));
  98806. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  98807. /**
  98808. * Defines an optimization based on user defined callback.
  98809. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98810. */
  98811. var CustomOptimization = /** @class */ (function (_super) {
  98812. __extends(CustomOptimization, _super);
  98813. function CustomOptimization() {
  98814. return _super !== null && _super.apply(this, arguments) || this;
  98815. }
  98816. /**
  98817. * Gets a string describing the action executed by the current optimization
  98818. * @returns description string
  98819. */
  98820. CustomOptimization.prototype.getDescription = function () {
  98821. if (this.onGetDescription) {
  98822. return this.onGetDescription();
  98823. }
  98824. return "Running user defined callback";
  98825. };
  98826. /**
  98827. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98828. * @param scene defines the current scene where to apply this optimization
  98829. * @param optimizer defines the current optimizer
  98830. * @returns true if everything that can be done was applied
  98831. */
  98832. CustomOptimization.prototype.apply = function (scene, optimizer) {
  98833. if (this.onApply) {
  98834. return this.onApply(scene, optimizer);
  98835. }
  98836. return true;
  98837. };
  98838. ;
  98839. return CustomOptimization;
  98840. }(SceneOptimization));
  98841. BABYLON.CustomOptimization = CustomOptimization;
  98842. /**
  98843. * Defines an optimization used to turn particles off
  98844. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98845. */
  98846. var ParticlesOptimization = /** @class */ (function (_super) {
  98847. __extends(ParticlesOptimization, _super);
  98848. function ParticlesOptimization() {
  98849. return _super !== null && _super.apply(this, arguments) || this;
  98850. }
  98851. /**
  98852. * Gets a string describing the action executed by the current optimization
  98853. * @return description string
  98854. */
  98855. ParticlesOptimization.prototype.getDescription = function () {
  98856. return "Turning particles on/off";
  98857. };
  98858. /**
  98859. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98860. * @param scene defines the current scene where to apply this optimization
  98861. * @param optimizer defines the current optimizer
  98862. * @returns true if everything that can be done was applied
  98863. */
  98864. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  98865. scene.particlesEnabled = optimizer.isInImprovementMode;
  98866. return true;
  98867. };
  98868. ;
  98869. return ParticlesOptimization;
  98870. }(SceneOptimization));
  98871. BABYLON.ParticlesOptimization = ParticlesOptimization;
  98872. /**
  98873. * Defines an optimization used to turn render targets off
  98874. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98875. */
  98876. var RenderTargetsOptimization = /** @class */ (function (_super) {
  98877. __extends(RenderTargetsOptimization, _super);
  98878. function RenderTargetsOptimization() {
  98879. return _super !== null && _super.apply(this, arguments) || this;
  98880. }
  98881. /**
  98882. * Gets a string describing the action executed by the current optimization
  98883. * @return description string
  98884. */
  98885. RenderTargetsOptimization.prototype.getDescription = function () {
  98886. return "Turning render targets off";
  98887. };
  98888. /**
  98889. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98890. * @param scene defines the current scene where to apply this optimization
  98891. * @param optimizer defines the current optimizer
  98892. * @returns true if everything that can be done was applied
  98893. */
  98894. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  98895. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  98896. return true;
  98897. };
  98898. ;
  98899. return RenderTargetsOptimization;
  98900. }(SceneOptimization));
  98901. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  98902. /**
  98903. * Defines an optimization used to merge meshes with compatible materials
  98904. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98905. */
  98906. var MergeMeshesOptimization = /** @class */ (function (_super) {
  98907. __extends(MergeMeshesOptimization, _super);
  98908. function MergeMeshesOptimization() {
  98909. var _this = _super !== null && _super.apply(this, arguments) || this;
  98910. _this._canBeMerged = function (abstractMesh) {
  98911. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  98912. return false;
  98913. }
  98914. var mesh = abstractMesh;
  98915. if (mesh.isDisposed()) {
  98916. return false;
  98917. }
  98918. if (!mesh.isVisible || !mesh.isEnabled()) {
  98919. return false;
  98920. }
  98921. if (mesh.instances.length > 0) {
  98922. return false;
  98923. }
  98924. if (mesh.skeleton || mesh.hasLODLevels) {
  98925. return false;
  98926. }
  98927. return true;
  98928. };
  98929. return _this;
  98930. }
  98931. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  98932. /**
  98933. * Gets or sets a boolean which defines if optimization octree has to be updated
  98934. */
  98935. get: function () {
  98936. return MergeMeshesOptimization._UpdateSelectionTree;
  98937. },
  98938. /**
  98939. * Gets or sets a boolean which defines if optimization octree has to be updated
  98940. */
  98941. set: function (value) {
  98942. MergeMeshesOptimization._UpdateSelectionTree = value;
  98943. },
  98944. enumerable: true,
  98945. configurable: true
  98946. });
  98947. /**
  98948. * Gets a string describing the action executed by the current optimization
  98949. * @return description string
  98950. */
  98951. MergeMeshesOptimization.prototype.getDescription = function () {
  98952. return "Merging similar meshes together";
  98953. };
  98954. /**
  98955. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98956. * @param scene defines the current scene where to apply this optimization
  98957. * @param optimizer defines the current optimizer
  98958. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  98959. * @returns true if everything that can be done was applied
  98960. */
  98961. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  98962. var globalPool = scene.meshes.slice(0);
  98963. var globalLength = globalPool.length;
  98964. for (var index = 0; index < globalLength; index++) {
  98965. var currentPool = new Array();
  98966. var current = globalPool[index];
  98967. // Checks
  98968. if (!this._canBeMerged(current)) {
  98969. continue;
  98970. }
  98971. currentPool.push(current);
  98972. // Find compatible meshes
  98973. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  98974. var otherMesh = globalPool[subIndex];
  98975. if (!this._canBeMerged(otherMesh)) {
  98976. continue;
  98977. }
  98978. if (otherMesh.material !== current.material) {
  98979. continue;
  98980. }
  98981. if (otherMesh.checkCollisions !== current.checkCollisions) {
  98982. continue;
  98983. }
  98984. currentPool.push(otherMesh);
  98985. globalLength--;
  98986. globalPool.splice(subIndex, 1);
  98987. subIndex--;
  98988. }
  98989. if (currentPool.length < 2) {
  98990. continue;
  98991. }
  98992. // Merge meshes
  98993. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  98994. }
  98995. if (updateSelectionTree != undefined) {
  98996. if (updateSelectionTree) {
  98997. scene.createOrUpdateSelectionOctree();
  98998. }
  98999. }
  99000. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  99001. scene.createOrUpdateSelectionOctree();
  99002. }
  99003. return true;
  99004. };
  99005. ;
  99006. MergeMeshesOptimization._UpdateSelectionTree = false;
  99007. return MergeMeshesOptimization;
  99008. }(SceneOptimization));
  99009. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  99010. /**
  99011. * Defines a list of options used by SceneOptimizer
  99012. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99013. */
  99014. var SceneOptimizerOptions = /** @class */ (function () {
  99015. /**
  99016. * Creates a new list of options used by SceneOptimizer
  99017. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  99018. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  99019. */
  99020. function SceneOptimizerOptions(
  99021. /**
  99022. * Defines the target frame rate to reach (60 by default)
  99023. */
  99024. targetFrameRate,
  99025. /**
  99026. * Defines the interval between two checkes (2000ms by default)
  99027. */
  99028. trackerDuration) {
  99029. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  99030. if (trackerDuration === void 0) { trackerDuration = 2000; }
  99031. this.targetFrameRate = targetFrameRate;
  99032. this.trackerDuration = trackerDuration;
  99033. /**
  99034. * Gets the list of optimizations to apply
  99035. */
  99036. this.optimizations = new Array();
  99037. }
  99038. /**
  99039. * Add a new optimization
  99040. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  99041. * @returns the current SceneOptimizerOptions
  99042. */
  99043. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  99044. this.optimizations.push(optimization);
  99045. return this;
  99046. };
  99047. /**
  99048. * Add a new custom optimization
  99049. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  99050. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  99051. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  99052. * @returns the current SceneOptimizerOptions
  99053. */
  99054. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  99055. if (priority === void 0) { priority = 0; }
  99056. var optimization = new CustomOptimization(priority);
  99057. optimization.onApply = onApply;
  99058. optimization.onGetDescription = onGetDescription;
  99059. this.optimizations.push(optimization);
  99060. return this;
  99061. };
  99062. /**
  99063. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  99064. * @param targetFrameRate defines the target frame rate (60 by default)
  99065. * @returns a SceneOptimizerOptions object
  99066. */
  99067. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  99068. var result = new SceneOptimizerOptions(targetFrameRate);
  99069. var priority = 0;
  99070. result.addOptimization(new MergeMeshesOptimization(priority));
  99071. result.addOptimization(new ShadowsOptimization(priority));
  99072. result.addOptimization(new LensFlaresOptimization(priority));
  99073. // Next priority
  99074. priority++;
  99075. result.addOptimization(new PostProcessesOptimization(priority));
  99076. result.addOptimization(new ParticlesOptimization(priority));
  99077. // Next priority
  99078. priority++;
  99079. result.addOptimization(new TextureOptimization(priority, 1024));
  99080. return result;
  99081. };
  99082. /**
  99083. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  99084. * @param targetFrameRate defines the target frame rate (60 by default)
  99085. * @returns a SceneOptimizerOptions object
  99086. */
  99087. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  99088. var result = new SceneOptimizerOptions(targetFrameRate);
  99089. var priority = 0;
  99090. result.addOptimization(new MergeMeshesOptimization(priority));
  99091. result.addOptimization(new ShadowsOptimization(priority));
  99092. result.addOptimization(new LensFlaresOptimization(priority));
  99093. // Next priority
  99094. priority++;
  99095. result.addOptimization(new PostProcessesOptimization(priority));
  99096. result.addOptimization(new ParticlesOptimization(priority));
  99097. // Next priority
  99098. priority++;
  99099. result.addOptimization(new TextureOptimization(priority, 512));
  99100. // Next priority
  99101. priority++;
  99102. result.addOptimization(new RenderTargetsOptimization(priority));
  99103. // Next priority
  99104. priority++;
  99105. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  99106. return result;
  99107. };
  99108. /**
  99109. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  99110. * @param targetFrameRate defines the target frame rate (60 by default)
  99111. * @returns a SceneOptimizerOptions object
  99112. */
  99113. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  99114. var result = new SceneOptimizerOptions(targetFrameRate);
  99115. var priority = 0;
  99116. result.addOptimization(new MergeMeshesOptimization(priority));
  99117. result.addOptimization(new ShadowsOptimization(priority));
  99118. result.addOptimization(new LensFlaresOptimization(priority));
  99119. // Next priority
  99120. priority++;
  99121. result.addOptimization(new PostProcessesOptimization(priority));
  99122. result.addOptimization(new ParticlesOptimization(priority));
  99123. // Next priority
  99124. priority++;
  99125. result.addOptimization(new TextureOptimization(priority, 256));
  99126. // Next priority
  99127. priority++;
  99128. result.addOptimization(new RenderTargetsOptimization(priority));
  99129. // Next priority
  99130. priority++;
  99131. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  99132. return result;
  99133. };
  99134. return SceneOptimizerOptions;
  99135. }());
  99136. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  99137. /**
  99138. * Class used to run optimizations in order to reach a target frame rate
  99139. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99140. */
  99141. var SceneOptimizer = /** @class */ (function () {
  99142. /**
  99143. * Creates a new SceneOptimizer
  99144. * @param scene defines the scene to work on
  99145. * @param options defines the options to use with the SceneOptimizer
  99146. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  99147. * @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)
  99148. */
  99149. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  99150. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  99151. if (improvementMode === void 0) { improvementMode = false; }
  99152. var _this = this;
  99153. this._isRunning = false;
  99154. this._currentPriorityLevel = 0;
  99155. this._targetFrameRate = 60;
  99156. this._trackerDuration = 2000;
  99157. this._currentFrameRate = 0;
  99158. this._improvementMode = false;
  99159. /**
  99160. * Defines an observable called when the optimizer reaches the target frame rate
  99161. */
  99162. this.onSuccessObservable = new BABYLON.Observable();
  99163. /**
  99164. * Defines an observable called when the optimizer enables an optimization
  99165. */
  99166. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  99167. /**
  99168. * Defines an observable called when the optimizer is not able to reach the target frame rate
  99169. */
  99170. this.onFailureObservable = new BABYLON.Observable();
  99171. if (!options) {
  99172. this._options = new SceneOptimizerOptions();
  99173. }
  99174. else {
  99175. this._options = options;
  99176. }
  99177. if (this._options.targetFrameRate) {
  99178. this._targetFrameRate = this._options.targetFrameRate;
  99179. }
  99180. if (this._options.trackerDuration) {
  99181. this._trackerDuration = this._options.trackerDuration;
  99182. }
  99183. if (autoGeneratePriorities) {
  99184. var priority = 0;
  99185. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  99186. var optim = _a[_i];
  99187. optim.priority = priority++;
  99188. }
  99189. }
  99190. this._improvementMode = improvementMode;
  99191. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  99192. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  99193. _this._sceneDisposeObserver = null;
  99194. _this.dispose();
  99195. });
  99196. }
  99197. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  99198. /**
  99199. * Gets a boolean indicating if the optimizer is in improvement mode
  99200. */
  99201. get: function () {
  99202. return this._improvementMode;
  99203. },
  99204. enumerable: true,
  99205. configurable: true
  99206. });
  99207. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  99208. /**
  99209. * Gets the current priority level (0 at start)
  99210. */
  99211. get: function () {
  99212. return this._currentPriorityLevel;
  99213. },
  99214. enumerable: true,
  99215. configurable: true
  99216. });
  99217. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  99218. /**
  99219. * Gets the current frame rate checked by the SceneOptimizer
  99220. */
  99221. get: function () {
  99222. return this._currentFrameRate;
  99223. },
  99224. enumerable: true,
  99225. configurable: true
  99226. });
  99227. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  99228. /**
  99229. * Gets or sets the current target frame rate (60 by default)
  99230. */
  99231. get: function () {
  99232. return this._targetFrameRate;
  99233. },
  99234. /**
  99235. * Gets or sets the current target frame rate (60 by default)
  99236. */
  99237. set: function (value) {
  99238. this._targetFrameRate = value;
  99239. },
  99240. enumerable: true,
  99241. configurable: true
  99242. });
  99243. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  99244. /**
  99245. * Gets or sets the current interval between two checks (every 2000ms by default)
  99246. */
  99247. get: function () {
  99248. return this._trackerDuration;
  99249. },
  99250. /**
  99251. * Gets or sets the current interval between two checks (every 2000ms by default)
  99252. */
  99253. set: function (value) {
  99254. this._trackerDuration = value;
  99255. },
  99256. enumerable: true,
  99257. configurable: true
  99258. });
  99259. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  99260. /**
  99261. * Gets the list of active optimizations
  99262. */
  99263. get: function () {
  99264. return this._options.optimizations;
  99265. },
  99266. enumerable: true,
  99267. configurable: true
  99268. });
  99269. /**
  99270. * Stops the current optimizer
  99271. */
  99272. SceneOptimizer.prototype.stop = function () {
  99273. this._isRunning = false;
  99274. };
  99275. /**
  99276. * Reset the optimizer to initial step (current priority level = 0)
  99277. */
  99278. SceneOptimizer.prototype.reset = function () {
  99279. this._currentPriorityLevel = 0;
  99280. };
  99281. /**
  99282. * Start the optimizer. By default it will try to reach a specific framerate
  99283. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  99284. */
  99285. SceneOptimizer.prototype.start = function () {
  99286. var _this = this;
  99287. if (this._isRunning) {
  99288. return;
  99289. }
  99290. this._isRunning = true;
  99291. // Let's wait for the scene to be ready before running our check
  99292. this._scene.executeWhenReady(function () {
  99293. setTimeout(function () {
  99294. _this._checkCurrentState();
  99295. }, _this._trackerDuration);
  99296. });
  99297. };
  99298. SceneOptimizer.prototype._checkCurrentState = function () {
  99299. var _this = this;
  99300. if (!this._isRunning) {
  99301. return;
  99302. }
  99303. var scene = this._scene;
  99304. var options = this._options;
  99305. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  99306. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  99307. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  99308. this._isRunning = false;
  99309. this.onSuccessObservable.notifyObservers(this);
  99310. return;
  99311. }
  99312. // Apply current level of optimizations
  99313. var allDone = true;
  99314. var noOptimizationApplied = true;
  99315. for (var index = 0; index < options.optimizations.length; index++) {
  99316. var optimization = options.optimizations[index];
  99317. if (optimization.priority === this._currentPriorityLevel) {
  99318. noOptimizationApplied = false;
  99319. allDone = allDone && optimization.apply(scene, this);
  99320. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  99321. }
  99322. }
  99323. // If no optimization was applied, this is a failure :(
  99324. if (noOptimizationApplied) {
  99325. this._isRunning = false;
  99326. this.onFailureObservable.notifyObservers(this);
  99327. return;
  99328. }
  99329. // If all optimizations were done, move to next level
  99330. if (allDone) {
  99331. this._currentPriorityLevel++;
  99332. }
  99333. // Let's the system running for a specific amount of time before checking FPS
  99334. scene.executeWhenReady(function () {
  99335. setTimeout(function () {
  99336. _this._checkCurrentState();
  99337. }, _this._trackerDuration);
  99338. });
  99339. };
  99340. /**
  99341. * Release all resources
  99342. */
  99343. SceneOptimizer.prototype.dispose = function () {
  99344. this.stop();
  99345. this.onSuccessObservable.clear();
  99346. this.onFailureObservable.clear();
  99347. this.onNewOptimizationAppliedObservable.clear();
  99348. if (this._sceneDisposeObserver) {
  99349. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  99350. }
  99351. };
  99352. /**
  99353. * Helper function to create a SceneOptimizer with one single line of code
  99354. * @param scene defines the scene to work on
  99355. * @param options defines the options to use with the SceneOptimizer
  99356. * @param onSuccess defines a callback to call on success
  99357. * @param onFailure defines a callback to call on failure
  99358. * @returns the new SceneOptimizer object
  99359. */
  99360. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  99361. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  99362. if (onSuccess) {
  99363. optimizer.onSuccessObservable.add(function () {
  99364. onSuccess();
  99365. });
  99366. }
  99367. if (onFailure) {
  99368. optimizer.onFailureObservable.add(function () {
  99369. onFailure();
  99370. });
  99371. }
  99372. optimizer.start();
  99373. return optimizer;
  99374. };
  99375. return SceneOptimizer;
  99376. }());
  99377. BABYLON.SceneOptimizer = SceneOptimizer;
  99378. })(BABYLON || (BABYLON = {}));
  99379. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  99380. var BABYLON;
  99381. (function (BABYLON) {
  99382. var OutlineRenderer = /** @class */ (function () {
  99383. function OutlineRenderer(scene) {
  99384. this.zOffset = 1;
  99385. this._scene = scene;
  99386. }
  99387. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  99388. var _this = this;
  99389. if (useOverlay === void 0) { useOverlay = false; }
  99390. var scene = this._scene;
  99391. var engine = this._scene.getEngine();
  99392. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  99393. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  99394. return;
  99395. }
  99396. var mesh = subMesh.getRenderingMesh();
  99397. var material = subMesh.getMaterial();
  99398. if (!material || !scene.activeCamera) {
  99399. return;
  99400. }
  99401. engine.enableEffect(this._effect);
  99402. // Logarithmic depth
  99403. if (material.useLogarithmicDepth) {
  99404. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  99405. }
  99406. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  99407. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  99408. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  99409. // Bones
  99410. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  99411. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  99412. }
  99413. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  99414. // Alpha test
  99415. if (material && material.needAlphaTesting()) {
  99416. var alphaTexture = material.getAlphaTestTexture();
  99417. if (alphaTexture) {
  99418. this._effect.setTexture("diffuseSampler", alphaTexture);
  99419. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  99420. }
  99421. }
  99422. engine.setZOffset(-this.zOffset);
  99423. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  99424. engine.setZOffset(0);
  99425. };
  99426. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  99427. var defines = [];
  99428. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  99429. var mesh = subMesh.getMesh();
  99430. var material = subMesh.getMaterial();
  99431. if (material) {
  99432. // Alpha test
  99433. if (material.needAlphaTesting()) {
  99434. defines.push("#define ALPHATEST");
  99435. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  99436. attribs.push(BABYLON.VertexBuffer.UVKind);
  99437. defines.push("#define UV1");
  99438. }
  99439. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  99440. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  99441. defines.push("#define UV2");
  99442. }
  99443. }
  99444. //Logarithmic depth
  99445. if (material.useLogarithmicDepth) {
  99446. defines.push("#define LOGARITHMICDEPTH");
  99447. }
  99448. }
  99449. // Bones
  99450. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  99451. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  99452. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  99453. if (mesh.numBoneInfluencers > 4) {
  99454. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  99455. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  99456. }
  99457. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  99458. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  99459. }
  99460. else {
  99461. defines.push("#define NUM_BONE_INFLUENCERS 0");
  99462. }
  99463. // Instances
  99464. if (useInstances) {
  99465. defines.push("#define INSTANCES");
  99466. attribs.push("world0");
  99467. attribs.push("world1");
  99468. attribs.push("world2");
  99469. attribs.push("world3");
  99470. }
  99471. // Get correct effect
  99472. var join = defines.join("\n");
  99473. if (this._cachedDefines !== join) {
  99474. this._cachedDefines = join;
  99475. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  99476. }
  99477. return this._effect.isReady();
  99478. };
  99479. return OutlineRenderer;
  99480. }());
  99481. BABYLON.OutlineRenderer = OutlineRenderer;
  99482. })(BABYLON || (BABYLON = {}));
  99483. //# sourceMappingURL=babylon.outlineRenderer.js.map
  99484. var BABYLON;
  99485. (function (BABYLON) {
  99486. /**
  99487. * FaceAdjacencies Helper class to generate edges
  99488. */
  99489. var FaceAdjacencies = /** @class */ (function () {
  99490. function FaceAdjacencies() {
  99491. this.edges = new Array();
  99492. this.edgesConnectedCount = 0;
  99493. }
  99494. return FaceAdjacencies;
  99495. }());
  99496. /**
  99497. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  99498. */
  99499. var EdgesRenderer = /** @class */ (function () {
  99500. /**
  99501. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  99502. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  99503. * @param source Mesh used to create edges
  99504. * @param epsilon sum of angles in adjacency to check for edge
  99505. * @param checkVerticesInsteadOfIndices
  99506. * @param generateEdgesLines - should generate Lines or only prepare resources.
  99507. */
  99508. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  99509. if (epsilon === void 0) { epsilon = 0.95; }
  99510. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  99511. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  99512. this.edgesWidthScalerForOrthographic = 1000.0;
  99513. this.edgesWidthScalerForPerspective = 50.0;
  99514. this._linesPositions = new Array();
  99515. this._linesNormals = new Array();
  99516. this._linesIndices = new Array();
  99517. this._buffers = {};
  99518. this._checkVerticesInsteadOfIndices = false;
  99519. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  99520. this.isEnabled = true;
  99521. this._source = source;
  99522. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  99523. this._epsilon = epsilon;
  99524. this._prepareRessources();
  99525. if (generateEdgesLines) {
  99526. this._generateEdgesLines();
  99527. }
  99528. }
  99529. EdgesRenderer.prototype._prepareRessources = function () {
  99530. if (this._lineShader) {
  99531. return;
  99532. }
  99533. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  99534. attributes: ["position", "normal"],
  99535. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  99536. });
  99537. this._lineShader.disableDepthWrite = true;
  99538. this._lineShader.backFaceCulling = false;
  99539. };
  99540. /** @hidden */
  99541. EdgesRenderer.prototype._rebuild = function () {
  99542. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  99543. if (buffer) {
  99544. buffer._rebuild();
  99545. }
  99546. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  99547. if (buffer) {
  99548. buffer._rebuild();
  99549. }
  99550. var scene = this._source.getScene();
  99551. var engine = scene.getEngine();
  99552. this._ib = engine.createIndexBuffer(this._linesIndices);
  99553. };
  99554. /**
  99555. * Releases the required resources for the edges renderer
  99556. */
  99557. EdgesRenderer.prototype.dispose = function () {
  99558. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  99559. if (buffer) {
  99560. buffer.dispose();
  99561. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  99562. }
  99563. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  99564. if (buffer) {
  99565. buffer.dispose();
  99566. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  99567. }
  99568. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  99569. this._lineShader.dispose();
  99570. };
  99571. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  99572. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  99573. return 0;
  99574. }
  99575. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  99576. return 1;
  99577. }
  99578. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  99579. return 2;
  99580. }
  99581. return -1;
  99582. };
  99583. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  99584. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  99585. return 0;
  99586. }
  99587. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  99588. return 1;
  99589. }
  99590. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  99591. return 2;
  99592. }
  99593. return -1;
  99594. };
  99595. /**
  99596. * Checks if the pair of p0 and p1 is en edge
  99597. * @param faceIndex
  99598. * @param edge
  99599. * @param faceNormals
  99600. * @param p0
  99601. * @param p1
  99602. * @private
  99603. */
  99604. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  99605. var needToCreateLine;
  99606. if (edge === undefined) {
  99607. needToCreateLine = true;
  99608. }
  99609. else {
  99610. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  99611. needToCreateLine = dotProduct < this._epsilon;
  99612. }
  99613. if (needToCreateLine) {
  99614. var offset = this._linesPositions.length / 3;
  99615. var normal = p0.subtract(p1);
  99616. normal.normalize();
  99617. // Positions
  99618. this._linesPositions.push(p0.x);
  99619. this._linesPositions.push(p0.y);
  99620. this._linesPositions.push(p0.z);
  99621. this._linesPositions.push(p0.x);
  99622. this._linesPositions.push(p0.y);
  99623. this._linesPositions.push(p0.z);
  99624. this._linesPositions.push(p1.x);
  99625. this._linesPositions.push(p1.y);
  99626. this._linesPositions.push(p1.z);
  99627. this._linesPositions.push(p1.x);
  99628. this._linesPositions.push(p1.y);
  99629. this._linesPositions.push(p1.z);
  99630. // Normals
  99631. this._linesNormals.push(p1.x);
  99632. this._linesNormals.push(p1.y);
  99633. this._linesNormals.push(p1.z);
  99634. this._linesNormals.push(-1);
  99635. this._linesNormals.push(p1.x);
  99636. this._linesNormals.push(p1.y);
  99637. this._linesNormals.push(p1.z);
  99638. this._linesNormals.push(1);
  99639. this._linesNormals.push(p0.x);
  99640. this._linesNormals.push(p0.y);
  99641. this._linesNormals.push(p0.z);
  99642. this._linesNormals.push(-1);
  99643. this._linesNormals.push(p0.x);
  99644. this._linesNormals.push(p0.y);
  99645. this._linesNormals.push(p0.z);
  99646. this._linesNormals.push(1);
  99647. // Indices
  99648. this._linesIndices.push(offset);
  99649. this._linesIndices.push(offset + 1);
  99650. this._linesIndices.push(offset + 2);
  99651. this._linesIndices.push(offset);
  99652. this._linesIndices.push(offset + 2);
  99653. this._linesIndices.push(offset + 3);
  99654. }
  99655. };
  99656. /**
  99657. * Generates lines edges from adjacencjes
  99658. * @private
  99659. */
  99660. EdgesRenderer.prototype._generateEdgesLines = function () {
  99661. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  99662. var indices = this._source.getIndices();
  99663. if (!indices || !positions) {
  99664. return;
  99665. }
  99666. // First let's find adjacencies
  99667. var adjacencies = new Array();
  99668. var faceNormals = new Array();
  99669. var index;
  99670. var faceAdjacencies;
  99671. // Prepare faces
  99672. for (index = 0; index < indices.length; index += 3) {
  99673. faceAdjacencies = new FaceAdjacencies();
  99674. var p0Index = indices[index];
  99675. var p1Index = indices[index + 1];
  99676. var p2Index = indices[index + 2];
  99677. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  99678. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  99679. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  99680. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  99681. faceNormal.normalize();
  99682. faceNormals.push(faceNormal);
  99683. adjacencies.push(faceAdjacencies);
  99684. }
  99685. // Scan
  99686. for (index = 0; index < adjacencies.length; index++) {
  99687. faceAdjacencies = adjacencies[index];
  99688. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  99689. var otherFaceAdjacencies = adjacencies[otherIndex];
  99690. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  99691. break;
  99692. }
  99693. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  99694. continue;
  99695. }
  99696. var otherP0 = indices[otherIndex * 3];
  99697. var otherP1 = indices[otherIndex * 3 + 1];
  99698. var otherP2 = indices[otherIndex * 3 + 2];
  99699. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  99700. var otherEdgeIndex = 0;
  99701. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  99702. continue;
  99703. }
  99704. switch (edgeIndex) {
  99705. case 0:
  99706. if (this._checkVerticesInsteadOfIndices) {
  99707. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  99708. }
  99709. else {
  99710. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  99711. }
  99712. break;
  99713. case 1:
  99714. if (this._checkVerticesInsteadOfIndices) {
  99715. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  99716. }
  99717. else {
  99718. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  99719. }
  99720. break;
  99721. case 2:
  99722. if (this._checkVerticesInsteadOfIndices) {
  99723. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  99724. }
  99725. else {
  99726. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  99727. }
  99728. break;
  99729. }
  99730. if (otherEdgeIndex === -1) {
  99731. continue;
  99732. }
  99733. faceAdjacencies.edges[edgeIndex] = otherIndex;
  99734. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  99735. faceAdjacencies.edgesConnectedCount++;
  99736. otherFaceAdjacencies.edgesConnectedCount++;
  99737. if (faceAdjacencies.edgesConnectedCount === 3) {
  99738. break;
  99739. }
  99740. }
  99741. }
  99742. }
  99743. // Create lines
  99744. for (index = 0; index < adjacencies.length; index++) {
  99745. // 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
  99746. var current = adjacencies[index];
  99747. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  99748. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  99749. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  99750. }
  99751. // Merge into a single mesh
  99752. var engine = this._source.getScene().getEngine();
  99753. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  99754. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  99755. this._ib = engine.createIndexBuffer(this._linesIndices);
  99756. this._indicesCount = this._linesIndices.length;
  99757. };
  99758. EdgesRenderer.prototype.render = function () {
  99759. var scene = this._source.getScene();
  99760. if (!this._lineShader.isReady() || !scene.activeCamera) {
  99761. return;
  99762. }
  99763. var engine = scene.getEngine();
  99764. this._lineShader._preBind();
  99765. if (this._source.edgesColor.a !== 1) {
  99766. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  99767. }
  99768. else {
  99769. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  99770. }
  99771. // VBOs
  99772. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  99773. scene.resetCachedMaterial();
  99774. this._lineShader.setColor4("color", this._source.edgesColor);
  99775. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  99776. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  99777. }
  99778. else {
  99779. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  99780. }
  99781. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  99782. this._lineShader.bind(this._source.getWorldMatrix());
  99783. // Draw order
  99784. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  99785. this._lineShader.unbind();
  99786. };
  99787. return EdgesRenderer;
  99788. }());
  99789. BABYLON.EdgesRenderer = EdgesRenderer;
  99790. })(BABYLON || (BABYLON = {}));
  99791. //# sourceMappingURL=babylon.edgesRenderer.js.map
  99792. var BABYLON;
  99793. (function (BABYLON) {
  99794. /**
  99795. * FaceAdjacencies Helper class to generate edges
  99796. */
  99797. var FaceAdjacencies = /** @class */ (function () {
  99798. function FaceAdjacencies() {
  99799. this.edges = new Array();
  99800. this.edgesConnectedCount = 0;
  99801. }
  99802. return FaceAdjacencies;
  99803. }());
  99804. /**
  99805. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  99806. */
  99807. var LineEdgesRenderer = /** @class */ (function (_super) {
  99808. __extends(LineEdgesRenderer, _super);
  99809. /**
  99810. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  99811. * @param source LineMesh used to generate edges
  99812. * @param epsilon not important (specified angle for edge detection)
  99813. * @param checkVerticesInsteadOfIndices not important for LineMesh
  99814. */
  99815. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  99816. if (epsilon === void 0) { epsilon = 0.95; }
  99817. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  99818. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  99819. _this._generateEdgesLines();
  99820. return _this;
  99821. }
  99822. /**
  99823. * Always create the edge since its a line so only important things are p0 and p1
  99824. * @param faceIndex not important for LineMesh
  99825. * @param edge not important for LineMesh
  99826. * @param faceNormals not important for LineMesh
  99827. * @param p0 beginnig of line
  99828. * @param p1 end of line
  99829. */
  99830. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  99831. var offset = this._linesPositions.length / 3;
  99832. var normal = p0.subtract(p1);
  99833. normal.normalize();
  99834. // Positions
  99835. this._linesPositions.push(p0.x);
  99836. this._linesPositions.push(p0.y);
  99837. this._linesPositions.push(p0.z);
  99838. this._linesPositions.push(p0.x);
  99839. this._linesPositions.push(p0.y);
  99840. this._linesPositions.push(p0.z);
  99841. this._linesPositions.push(p1.x);
  99842. this._linesPositions.push(p1.y);
  99843. this._linesPositions.push(p1.z);
  99844. this._linesPositions.push(p1.x);
  99845. this._linesPositions.push(p1.y);
  99846. this._linesPositions.push(p1.z);
  99847. // Normals
  99848. this._linesNormals.push(p1.x);
  99849. this._linesNormals.push(p1.y);
  99850. this._linesNormals.push(p1.z);
  99851. this._linesNormals.push(-1);
  99852. this._linesNormals.push(p1.x);
  99853. this._linesNormals.push(p1.y);
  99854. this._linesNormals.push(p1.z);
  99855. this._linesNormals.push(1);
  99856. this._linesNormals.push(p0.x);
  99857. this._linesNormals.push(p0.y);
  99858. this._linesNormals.push(p0.z);
  99859. this._linesNormals.push(-1);
  99860. this._linesNormals.push(p0.x);
  99861. this._linesNormals.push(p0.y);
  99862. this._linesNormals.push(p0.z);
  99863. this._linesNormals.push(1);
  99864. // Indices
  99865. this._linesIndices.push(offset);
  99866. this._linesIndices.push(offset + 1);
  99867. this._linesIndices.push(offset + 2);
  99868. this._linesIndices.push(offset);
  99869. this._linesIndices.push(offset + 2);
  99870. this._linesIndices.push(offset + 3);
  99871. };
  99872. /**
  99873. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  99874. */
  99875. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  99876. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  99877. var indices = this._source.getIndices();
  99878. if (!indices || !positions) {
  99879. return;
  99880. }
  99881. // First let's find adjacencies
  99882. var adjacencies = new Array();
  99883. var faceNormals = new Array();
  99884. var index;
  99885. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  99886. var currentAdjecancy = new FaceAdjacencies();
  99887. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  99888. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  99889. adjacencies.push(currentAdjecancy);
  99890. }
  99891. // Create lines
  99892. for (index = 0; index < adjacencies.length; index++) {
  99893. // 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
  99894. var current = adjacencies[index];
  99895. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  99896. }
  99897. // Merge into a single mesh
  99898. var engine = this._source.getScene().getEngine();
  99899. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  99900. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  99901. this._ib = engine.createIndexBuffer(this._linesIndices);
  99902. this._indicesCount = this._linesIndices.length;
  99903. };
  99904. return LineEdgesRenderer;
  99905. }(BABYLON.EdgesRenderer));
  99906. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  99907. })(BABYLON || (BABYLON = {}));
  99908. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  99909. var BABYLON;
  99910. (function (BABYLON) {
  99911. // Adds the parser to the scene parsers.
  99912. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  99913. if (parsedData.effectLayers) {
  99914. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  99915. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  99916. container.effectLayers.push(effectLayer);
  99917. }
  99918. }
  99919. });
  99920. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  99921. var index = this.effectLayers.indexOf(toRemove);
  99922. if (index !== -1) {
  99923. this.effectLayers.splice(index, 1);
  99924. }
  99925. return index;
  99926. };
  99927. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  99928. this.effectLayers.push(newEffectLayer);
  99929. };
  99930. /**
  99931. * Defines the layer scene component responsible to manage any effect layers
  99932. * in a given scene.
  99933. */
  99934. var EffectLayerSceneComponent = /** @class */ (function () {
  99935. /**
  99936. * Creates a new instance of the component for the given scene
  99937. * @param scene Defines the scene to register the component in
  99938. */
  99939. function EffectLayerSceneComponent(scene) {
  99940. /**
  99941. * The component name helpfull to identify the component in the list of scene components.
  99942. */
  99943. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  99944. this._renderEffects = false;
  99945. this._needStencil = false;
  99946. this._previousStencilState = false;
  99947. this.scene = scene;
  99948. this._engine = scene.getEngine();
  99949. scene.effectLayers = new Array();
  99950. }
  99951. /**
  99952. * Registers the component in a given scene
  99953. */
  99954. EffectLayerSceneComponent.prototype.register = function () {
  99955. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  99956. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  99957. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  99958. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  99959. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  99960. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  99961. };
  99962. /**
  99963. * Rebuilds the elements related to this component in case of
  99964. * context lost for instance.
  99965. */
  99966. EffectLayerSceneComponent.prototype.rebuild = function () {
  99967. var layers = this.scene.effectLayers;
  99968. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  99969. var effectLayer = layers_1[_i];
  99970. effectLayer._rebuild();
  99971. }
  99972. };
  99973. /**
  99974. * Serializes the component data to the specified json object
  99975. * @param serializationObject The object to serialize to
  99976. */
  99977. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  99978. // Effect layers
  99979. serializationObject.effectLayers = [];
  99980. var layers = this.scene.effectLayers;
  99981. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  99982. var effectLayer = layers_2[_i];
  99983. if (effectLayer.serialize) {
  99984. serializationObject.effectLayers.push(effectLayer.serialize());
  99985. }
  99986. }
  99987. };
  99988. /**
  99989. * Adds all the element from the container to the scene
  99990. * @param container the container holding the elements
  99991. */
  99992. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  99993. var _this = this;
  99994. if (!container.effectLayers) {
  99995. return;
  99996. }
  99997. container.effectLayers.forEach(function (o) {
  99998. _this.scene.addEffectLayer(o);
  99999. });
  100000. };
  100001. /**
  100002. * Removes all the elements in the container from the scene
  100003. * @param container contains the elements to remove
  100004. */
  100005. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  100006. var _this = this;
  100007. if (!container.effectLayers) {
  100008. return;
  100009. }
  100010. container.effectLayers.forEach(function (o) {
  100011. _this.scene.removeEffectLayer(o);
  100012. });
  100013. };
  100014. /**
  100015. * Disposes the component and the associated ressources.
  100016. */
  100017. EffectLayerSceneComponent.prototype.dispose = function () {
  100018. var layers = this.scene.effectLayers;
  100019. while (layers.length) {
  100020. layers[0].dispose();
  100021. }
  100022. };
  100023. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  100024. var layers = this.scene.effectLayers;
  100025. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  100026. var layer = layers_3[_i];
  100027. if (!layer.hasMesh(mesh)) {
  100028. continue;
  100029. }
  100030. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  100031. var subMesh = _b[_a];
  100032. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  100033. return false;
  100034. }
  100035. }
  100036. }
  100037. return true;
  100038. };
  100039. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  100040. this._renderEffects = false;
  100041. this._needStencil = false;
  100042. var layers = this.scene.effectLayers;
  100043. if (layers && layers.length > 0) {
  100044. this._previousStencilState = this._engine.getStencilBuffer();
  100045. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  100046. var effectLayer = layers_4[_i];
  100047. if (effectLayer.shouldRender() &&
  100048. (!effectLayer.camera ||
  100049. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  100050. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  100051. this._renderEffects = true;
  100052. this._needStencil = this._needStencil || effectLayer.needStencil();
  100053. var renderTarget = effectLayer._mainTexture;
  100054. if (renderTarget._shouldRender()) {
  100055. this.scene.incrementRenderId();
  100056. renderTarget.render(false, false);
  100057. }
  100058. }
  100059. }
  100060. this.scene.incrementRenderId();
  100061. }
  100062. };
  100063. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  100064. // Activate effect Layer stencil
  100065. if (this._needStencil) {
  100066. this._engine.setStencilBuffer(true);
  100067. }
  100068. };
  100069. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  100070. // Restore effect Layer stencil
  100071. if (this._needStencil) {
  100072. this._engine.setStencilBuffer(this._previousStencilState);
  100073. }
  100074. };
  100075. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  100076. if (this._renderEffects) {
  100077. this._engine.setDepthBuffer(false);
  100078. var layers = this.scene.effectLayers;
  100079. for (var i = 0; i < layers.length; i++) {
  100080. var effectLayer = layers[i];
  100081. if (effectLayer.renderingGroupId === renderingGroupId) {
  100082. if (effectLayer.shouldRender()) {
  100083. effectLayer.render();
  100084. }
  100085. }
  100086. }
  100087. this._engine.setDepthBuffer(true);
  100088. }
  100089. };
  100090. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  100091. if (this._renderEffects) {
  100092. this._draw(-1);
  100093. }
  100094. };
  100095. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  100096. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  100097. this._draw(index);
  100098. }
  100099. };
  100100. return EffectLayerSceneComponent;
  100101. }());
  100102. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  100103. })(BABYLON || (BABYLON = {}));
  100104. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  100105. var __assign = (this && this.__assign) || function () {
  100106. __assign = Object.assign || function(t) {
  100107. for (var s, i = 1, n = arguments.length; i < n; i++) {
  100108. s = arguments[i];
  100109. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  100110. t[p] = s[p];
  100111. }
  100112. return t;
  100113. };
  100114. return __assign.apply(this, arguments);
  100115. };
  100116. var BABYLON;
  100117. (function (BABYLON) {
  100118. /**
  100119. * The effect layer Helps adding post process effect blended with the main pass.
  100120. *
  100121. * This can be for instance use to generate glow or higlight effects on the scene.
  100122. *
  100123. * The effect layer class can not be used directly and is intented to inherited from to be
  100124. * customized per effects.
  100125. */
  100126. var EffectLayer = /** @class */ (function () {
  100127. /**
  100128. * Instantiates a new effect Layer and references it in the scene.
  100129. * @param name The name of the layer
  100130. * @param scene The scene to use the layer in
  100131. */
  100132. function EffectLayer(
  100133. /** The Friendly of the effect in the scene */
  100134. name, scene) {
  100135. this._vertexBuffers = {};
  100136. this._maxSize = 0;
  100137. this._mainTextureDesiredSize = { width: 0, height: 0 };
  100138. this._shouldRender = true;
  100139. this._postProcesses = [];
  100140. this._textures = [];
  100141. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  100142. /**
  100143. * The clear color of the texture used to generate the glow map.
  100144. */
  100145. this.neutralColor = new BABYLON.Color4();
  100146. /**
  100147. * Specifies wether the highlight layer is enabled or not.
  100148. */
  100149. this.isEnabled = true;
  100150. /**
  100151. * An event triggered when the effect layer has been disposed.
  100152. */
  100153. this.onDisposeObservable = new BABYLON.Observable();
  100154. /**
  100155. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  100156. */
  100157. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  100158. /**
  100159. * An event triggered when the generated texture is being merged in the scene.
  100160. */
  100161. this.onBeforeComposeObservable = new BABYLON.Observable();
  100162. /**
  100163. * An event triggered when the generated texture has been merged in the scene.
  100164. */
  100165. this.onAfterComposeObservable = new BABYLON.Observable();
  100166. /**
  100167. * An event triggered when the efffect layer changes its size.
  100168. */
  100169. this.onSizeChangedObservable = new BABYLON.Observable();
  100170. this.name = name;
  100171. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  100172. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  100173. if (!component) {
  100174. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  100175. this._scene._addComponent(component);
  100176. }
  100177. this._engine = this._scene.getEngine();
  100178. this._maxSize = this._engine.getCaps().maxTextureSize;
  100179. this._scene.effectLayers.push(this);
  100180. // Generate Buffers
  100181. this._generateIndexBuffer();
  100182. this._genrateVertexBuffer();
  100183. }
  100184. Object.defineProperty(EffectLayer.prototype, "camera", {
  100185. /**
  100186. * Gets the camera attached to the layer.
  100187. */
  100188. get: function () {
  100189. return this._effectLayerOptions.camera;
  100190. },
  100191. enumerable: true,
  100192. configurable: true
  100193. });
  100194. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  100195. /**
  100196. * Gets the rendering group id the layer should render in.
  100197. */
  100198. get: function () {
  100199. return this._effectLayerOptions.renderingGroupId;
  100200. },
  100201. enumerable: true,
  100202. configurable: true
  100203. });
  100204. /**
  100205. * Initializes the effect layer with the required options.
  100206. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  100207. */
  100208. EffectLayer.prototype._init = function (options) {
  100209. // Adapt options
  100210. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  100211. this._setMainTextureSize();
  100212. this._createMainTexture();
  100213. this._createTextureAndPostProcesses();
  100214. this._mergeEffect = this._createMergeEffect();
  100215. };
  100216. /**
  100217. * Generates the index buffer of the full screen quad blending to the main canvas.
  100218. */
  100219. EffectLayer.prototype._generateIndexBuffer = function () {
  100220. // Indices
  100221. var indices = [];
  100222. indices.push(0);
  100223. indices.push(1);
  100224. indices.push(2);
  100225. indices.push(0);
  100226. indices.push(2);
  100227. indices.push(3);
  100228. this._indexBuffer = this._engine.createIndexBuffer(indices);
  100229. };
  100230. /**
  100231. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  100232. */
  100233. EffectLayer.prototype._genrateVertexBuffer = function () {
  100234. // VBO
  100235. var vertices = [];
  100236. vertices.push(1, 1);
  100237. vertices.push(-1, 1);
  100238. vertices.push(-1, -1);
  100239. vertices.push(1, -1);
  100240. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  100241. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  100242. };
  100243. /**
  100244. * Sets the main texture desired size which is the closest power of two
  100245. * of the engine canvas size.
  100246. */
  100247. EffectLayer.prototype._setMainTextureSize = function () {
  100248. if (this._effectLayerOptions.mainTextureFixedSize) {
  100249. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  100250. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  100251. }
  100252. else {
  100253. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  100254. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  100255. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  100256. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  100257. }
  100258. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  100259. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  100260. };
  100261. /**
  100262. * Creates the main texture for the effect layer.
  100263. */
  100264. EffectLayer.prototype._createMainTexture = function () {
  100265. var _this = this;
  100266. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  100267. width: this._mainTextureDesiredSize.width,
  100268. height: this._mainTextureDesiredSize.height
  100269. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  100270. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  100271. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100272. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100273. this._mainTexture.anisotropicFilteringLevel = 1;
  100274. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  100275. this._mainTexture.renderParticles = false;
  100276. this._mainTexture.renderList = null;
  100277. this._mainTexture.ignoreCameraViewport = true;
  100278. // Custom render function
  100279. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  100280. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  100281. var index;
  100282. var engine = _this._scene.getEngine();
  100283. if (depthOnlySubMeshes.length) {
  100284. engine.setColorWrite(false);
  100285. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  100286. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  100287. }
  100288. engine.setColorWrite(true);
  100289. }
  100290. for (index = 0; index < opaqueSubMeshes.length; index++) {
  100291. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  100292. }
  100293. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  100294. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  100295. }
  100296. for (index = 0; index < transparentSubMeshes.length; index++) {
  100297. _this._renderSubMesh(transparentSubMeshes.data[index]);
  100298. }
  100299. };
  100300. this._mainTexture.onClearObservable.add(function (engine) {
  100301. engine.clear(_this.neutralColor, true, true, true);
  100302. });
  100303. };
  100304. /**
  100305. * Checks for the readiness of the element composing the layer.
  100306. * @param subMesh the mesh to check for
  100307. * @param useInstances specify wether or not to use instances to render the mesh
  100308. * @param emissiveTexture the associated emissive texture used to generate the glow
  100309. * @return true if ready otherwise, false
  100310. */
  100311. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  100312. var material = subMesh.getMaterial();
  100313. if (!material) {
  100314. return false;
  100315. }
  100316. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  100317. return false;
  100318. }
  100319. var defines = [];
  100320. var attribs = [BABYLON.VertexBuffer.PositionKind];
  100321. var mesh = subMesh.getMesh();
  100322. var uv1 = false;
  100323. var uv2 = false;
  100324. // Alpha test
  100325. if (material && material.needAlphaTesting()) {
  100326. var alphaTexture = material.getAlphaTestTexture();
  100327. if (alphaTexture) {
  100328. defines.push("#define ALPHATEST");
  100329. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  100330. alphaTexture.coordinatesIndex === 1) {
  100331. defines.push("#define DIFFUSEUV2");
  100332. uv2 = true;
  100333. }
  100334. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  100335. defines.push("#define DIFFUSEUV1");
  100336. uv1 = true;
  100337. }
  100338. }
  100339. }
  100340. // Emissive
  100341. if (emissiveTexture) {
  100342. defines.push("#define EMISSIVE");
  100343. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  100344. emissiveTexture.coordinatesIndex === 1) {
  100345. defines.push("#define EMISSIVEUV2");
  100346. uv2 = true;
  100347. }
  100348. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  100349. defines.push("#define EMISSIVEUV1");
  100350. uv1 = true;
  100351. }
  100352. }
  100353. if (uv1) {
  100354. attribs.push(BABYLON.VertexBuffer.UVKind);
  100355. defines.push("#define UV1");
  100356. }
  100357. if (uv2) {
  100358. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  100359. defines.push("#define UV2");
  100360. }
  100361. // Bones
  100362. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  100363. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  100364. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  100365. if (mesh.numBoneInfluencers > 4) {
  100366. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  100367. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  100368. }
  100369. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  100370. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  100371. }
  100372. else {
  100373. defines.push("#define NUM_BONE_INFLUENCERS 0");
  100374. }
  100375. // Morph targets
  100376. var manager = mesh.morphTargetManager;
  100377. var morphInfluencers = 0;
  100378. if (manager) {
  100379. if (manager.numInfluencers > 0) {
  100380. defines.push("#define MORPHTARGETS");
  100381. morphInfluencers = manager.numInfluencers;
  100382. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  100383. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  100384. }
  100385. }
  100386. // Instances
  100387. if (useInstances) {
  100388. defines.push("#define INSTANCES");
  100389. attribs.push("world0");
  100390. attribs.push("world1");
  100391. attribs.push("world2");
  100392. attribs.push("world3");
  100393. }
  100394. // Get correct effect
  100395. var join = defines.join("\n");
  100396. if (this._cachedDefines !== join) {
  100397. this._cachedDefines = join;
  100398. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  100399. }
  100400. return this._effectLayerMapGenerationEffect.isReady();
  100401. };
  100402. /**
  100403. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  100404. */
  100405. EffectLayer.prototype.render = function () {
  100406. var currentEffect = this._mergeEffect;
  100407. // Check
  100408. if (!currentEffect.isReady())
  100409. return;
  100410. for (var i = 0; i < this._postProcesses.length; i++) {
  100411. if (!this._postProcesses[i].isReady()) {
  100412. return;
  100413. }
  100414. }
  100415. var engine = this._scene.getEngine();
  100416. this.onBeforeComposeObservable.notifyObservers(this);
  100417. // Render
  100418. engine.enableEffect(currentEffect);
  100419. engine.setState(false);
  100420. // VBOs
  100421. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  100422. // Cache
  100423. var previousAlphaMode = engine.getAlphaMode();
  100424. // Go Blend.
  100425. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  100426. // Blends the map on the main canvas.
  100427. this._internalRender(currentEffect);
  100428. // Restore Alpha
  100429. engine.setAlphaMode(previousAlphaMode);
  100430. this.onAfterComposeObservable.notifyObservers(this);
  100431. // Handle size changes.
  100432. var size = this._mainTexture.getSize();
  100433. this._setMainTextureSize();
  100434. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  100435. // Recreate RTT and post processes on size change.
  100436. this.onSizeChangedObservable.notifyObservers(this);
  100437. this._disposeTextureAndPostProcesses();
  100438. this._createMainTexture();
  100439. this._createTextureAndPostProcesses();
  100440. }
  100441. };
  100442. /**
  100443. * Determine if a given mesh will be used in the current effect.
  100444. * @param mesh mesh to test
  100445. * @returns true if the mesh will be used
  100446. */
  100447. EffectLayer.prototype.hasMesh = function (mesh) {
  100448. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  100449. return true;
  100450. }
  100451. return false;
  100452. };
  100453. /**
  100454. * Returns true if the layer contains information to display, otherwise false.
  100455. * @returns true if the glow layer should be rendered
  100456. */
  100457. EffectLayer.prototype.shouldRender = function () {
  100458. return this.isEnabled && this._shouldRender;
  100459. };
  100460. /**
  100461. * Returns true if the mesh should render, otherwise false.
  100462. * @param mesh The mesh to render
  100463. * @returns true if it should render otherwise false
  100464. */
  100465. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  100466. return true;
  100467. };
  100468. /**
  100469. * Returns true if the mesh should render, otherwise false.
  100470. * @param mesh The mesh to render
  100471. * @returns true if it should render otherwise false
  100472. */
  100473. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  100474. return true;
  100475. };
  100476. /**
  100477. * Renders the submesh passed in parameter to the generation map.
  100478. */
  100479. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  100480. var _this = this;
  100481. if (!this.shouldRender()) {
  100482. return;
  100483. }
  100484. var material = subMesh.getMaterial();
  100485. var mesh = subMesh.getRenderingMesh();
  100486. var scene = this._scene;
  100487. var engine = scene.getEngine();
  100488. if (!material) {
  100489. return;
  100490. }
  100491. // Do not block in blend mode.
  100492. if (material.needAlphaBlendingForMesh(mesh)) {
  100493. return;
  100494. }
  100495. // Culling
  100496. engine.setState(material.backFaceCulling);
  100497. // Managing instances
  100498. var batch = mesh._getInstancesRenderList(subMesh._id);
  100499. if (batch.mustReturn) {
  100500. return;
  100501. }
  100502. // Early Exit per mesh
  100503. if (!this._shouldRenderMesh(mesh)) {
  100504. return;
  100505. }
  100506. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  100507. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  100508. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  100509. engine.enableEffect(this._effectLayerMapGenerationEffect);
  100510. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  100511. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  100512. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  100513. // Alpha test
  100514. if (material && material.needAlphaTesting()) {
  100515. var alphaTexture = material.getAlphaTestTexture();
  100516. if (alphaTexture) {
  100517. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  100518. var textureMatrix = alphaTexture.getTextureMatrix();
  100519. if (textureMatrix) {
  100520. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  100521. }
  100522. }
  100523. }
  100524. // Glow emissive only
  100525. if (this._emissiveTextureAndColor.texture) {
  100526. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  100527. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  100528. }
  100529. // Bones
  100530. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  100531. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  100532. }
  100533. // Morph targets
  100534. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  100535. // Draw
  100536. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  100537. }
  100538. else {
  100539. // Need to reset refresh rate of the main map
  100540. this._mainTexture.resetRefreshCounter();
  100541. }
  100542. };
  100543. /**
  100544. * Rebuild the required buffers.
  100545. * @hidden Internal use only.
  100546. */
  100547. EffectLayer.prototype._rebuild = function () {
  100548. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  100549. if (vb) {
  100550. vb._rebuild();
  100551. }
  100552. this._generateIndexBuffer();
  100553. };
  100554. /**
  100555. * Dispose only the render target textures and post process.
  100556. */
  100557. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  100558. this._mainTexture.dispose();
  100559. for (var i = 0; i < this._postProcesses.length; i++) {
  100560. if (this._postProcesses[i]) {
  100561. this._postProcesses[i].dispose();
  100562. }
  100563. }
  100564. this._postProcesses = [];
  100565. for (var i = 0; i < this._textures.length; i++) {
  100566. if (this._textures[i]) {
  100567. this._textures[i].dispose();
  100568. }
  100569. }
  100570. this._textures = [];
  100571. };
  100572. /**
  100573. * Dispose the highlight layer and free resources.
  100574. */
  100575. EffectLayer.prototype.dispose = function () {
  100576. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  100577. if (vertexBuffer) {
  100578. vertexBuffer.dispose();
  100579. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  100580. }
  100581. if (this._indexBuffer) {
  100582. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  100583. this._indexBuffer = null;
  100584. }
  100585. // Clean textures and post processes
  100586. this._disposeTextureAndPostProcesses();
  100587. // Remove from scene
  100588. var index = this._scene.effectLayers.indexOf(this, 0);
  100589. if (index > -1) {
  100590. this._scene.effectLayers.splice(index, 1);
  100591. }
  100592. // Callback
  100593. this.onDisposeObservable.notifyObservers(this);
  100594. this.onDisposeObservable.clear();
  100595. this.onBeforeRenderMainTextureObservable.clear();
  100596. this.onBeforeComposeObservable.clear();
  100597. this.onAfterComposeObservable.clear();
  100598. this.onSizeChangedObservable.clear();
  100599. };
  100600. /**
  100601. * Gets the class name of the effect layer
  100602. * @returns the string with the class name of the effect layer
  100603. */
  100604. EffectLayer.prototype.getClassName = function () {
  100605. return "EffectLayer";
  100606. };
  100607. /**
  100608. * Creates an effect layer from parsed effect layer data
  100609. * @param parsedEffectLayer defines effect layer data
  100610. * @param scene defines the current scene
  100611. * @param rootUrl defines the root URL containing the effect layer information
  100612. * @returns a parsed effect Layer
  100613. */
  100614. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  100615. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  100616. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  100617. };
  100618. __decorate([
  100619. BABYLON.serialize()
  100620. ], EffectLayer.prototype, "name", void 0);
  100621. __decorate([
  100622. BABYLON.serializeAsColor4()
  100623. ], EffectLayer.prototype, "neutralColor", void 0);
  100624. __decorate([
  100625. BABYLON.serialize()
  100626. ], EffectLayer.prototype, "isEnabled", void 0);
  100627. __decorate([
  100628. BABYLON.serializeAsCameraReference()
  100629. ], EffectLayer.prototype, "camera", null);
  100630. __decorate([
  100631. BABYLON.serialize()
  100632. ], EffectLayer.prototype, "renderingGroupId", null);
  100633. return EffectLayer;
  100634. }());
  100635. BABYLON.EffectLayer = EffectLayer;
  100636. })(BABYLON || (BABYLON = {}));
  100637. //# sourceMappingURL=babylon.effectLayer.js.map
  100638. var BABYLON;
  100639. (function (BABYLON) {
  100640. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  100641. for (var index = 0; index < this.effectLayers.length; index++) {
  100642. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  100643. return this.effectLayers[index];
  100644. }
  100645. }
  100646. return null;
  100647. };
  100648. /**
  100649. * Special Glow Blur post process only blurring the alpha channel
  100650. * It enforces keeping the most luminous color in the color channel.
  100651. */
  100652. var GlowBlurPostProcess = /** @class */ (function (_super) {
  100653. __extends(GlowBlurPostProcess, _super);
  100654. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  100655. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  100656. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  100657. _this.direction = direction;
  100658. _this.kernel = kernel;
  100659. _this.onApplyObservable.add(function (effect) {
  100660. effect.setFloat2("screenSize", _this.width, _this.height);
  100661. effect.setVector2("direction", _this.direction);
  100662. effect.setFloat("blurWidth", _this.kernel);
  100663. });
  100664. return _this;
  100665. }
  100666. return GlowBlurPostProcess;
  100667. }(BABYLON.PostProcess));
  100668. /**
  100669. * The highlight layer Helps adding a glow effect around a mesh.
  100670. *
  100671. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  100672. * glowy meshes to your scene.
  100673. *
  100674. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  100675. */
  100676. var HighlightLayer = /** @class */ (function (_super) {
  100677. __extends(HighlightLayer, _super);
  100678. /**
  100679. * Instantiates a new highlight Layer and references it to the scene..
  100680. * @param name The name of the layer
  100681. * @param scene The scene to use the layer in
  100682. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  100683. */
  100684. function HighlightLayer(name, scene, options) {
  100685. var _this = _super.call(this, name, scene) || this;
  100686. _this.name = name;
  100687. /**
  100688. * Specifies whether or not the inner glow is ACTIVE in the layer.
  100689. */
  100690. _this.innerGlow = true;
  100691. /**
  100692. * Specifies whether or not the outer glow is ACTIVE in the layer.
  100693. */
  100694. _this.outerGlow = true;
  100695. /**
  100696. * An event triggered when the highlight layer is being blurred.
  100697. */
  100698. _this.onBeforeBlurObservable = new BABYLON.Observable();
  100699. /**
  100700. * An event triggered when the highlight layer has been blurred.
  100701. */
  100702. _this.onAfterBlurObservable = new BABYLON.Observable();
  100703. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  100704. _this._meshes = {};
  100705. _this._excludedMeshes = {};
  100706. _this.neutralColor = HighlightLayer.NeutralColor;
  100707. // Warn on stencil
  100708. if (!_this._engine.isStencilEnable) {
  100709. 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 }");
  100710. }
  100711. // Adapt options
  100712. _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);
  100713. // Initialize the layer
  100714. _this._init({
  100715. alphaBlendingMode: _this._options.alphaBlendingMode,
  100716. camera: _this._options.camera,
  100717. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  100718. mainTextureRatio: _this._options.mainTextureRatio,
  100719. renderingGroupId: _this._options.renderingGroupId
  100720. });
  100721. // Do not render as long as no meshes have been added
  100722. _this._shouldRender = false;
  100723. return _this;
  100724. }
  100725. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  100726. /**
  100727. * Gets the horizontal size of the blur.
  100728. */
  100729. get: function () {
  100730. return this._horizontalBlurPostprocess.kernel;
  100731. },
  100732. /**
  100733. * Specifies the horizontal size of the blur.
  100734. */
  100735. set: function (value) {
  100736. this._horizontalBlurPostprocess.kernel = value;
  100737. },
  100738. enumerable: true,
  100739. configurable: true
  100740. });
  100741. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  100742. /**
  100743. * Gets the vertical size of the blur.
  100744. */
  100745. get: function () {
  100746. return this._verticalBlurPostprocess.kernel;
  100747. },
  100748. /**
  100749. * Specifies the vertical size of the blur.
  100750. */
  100751. set: function (value) {
  100752. this._verticalBlurPostprocess.kernel = value;
  100753. },
  100754. enumerable: true,
  100755. configurable: true
  100756. });
  100757. /**
  100758. * Get the effect name of the layer.
  100759. * @return The effect name
  100760. */
  100761. HighlightLayer.prototype.getEffectName = function () {
  100762. return HighlightLayer.EffectName;
  100763. };
  100764. /**
  100765. * Create the merge effect. This is the shader use to blit the information back
  100766. * to the main canvas at the end of the scene rendering.
  100767. */
  100768. HighlightLayer.prototype._createMergeEffect = function () {
  100769. // Effect
  100770. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  100771. };
  100772. /**
  100773. * Creates the render target textures and post processes used in the highlight layer.
  100774. */
  100775. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  100776. var _this = this;
  100777. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  100778. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  100779. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  100780. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  100781. var textureType = 0;
  100782. if (this._engine.getCaps().textureHalfFloatRender) {
  100783. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  100784. }
  100785. else {
  100786. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100787. }
  100788. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  100789. width: blurTextureWidth,
  100790. height: blurTextureHeight
  100791. }, this._scene, false, true, textureType);
  100792. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100793. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100794. this._blurTexture.anisotropicFilteringLevel = 16;
  100795. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  100796. this._blurTexture.renderParticles = false;
  100797. this._blurTexture.ignoreCameraViewport = true;
  100798. this._textures = [this._blurTexture];
  100799. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  100800. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  100801. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  100802. effect.setTexture("textureSampler", _this._mainTexture);
  100803. });
  100804. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  100805. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  100806. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  100807. });
  100808. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  100809. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  100810. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  100811. });
  100812. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  100813. }
  100814. else {
  100815. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  100816. width: blurTextureWidth,
  100817. height: blurTextureHeight
  100818. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  100819. this._horizontalBlurPostprocess.width = blurTextureWidth;
  100820. this._horizontalBlurPostprocess.height = blurTextureHeight;
  100821. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  100822. effect.setTexture("textureSampler", _this._mainTexture);
  100823. });
  100824. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  100825. width: blurTextureWidth,
  100826. height: blurTextureHeight
  100827. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  100828. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  100829. }
  100830. this._mainTexture.onAfterUnbindObservable.add(function () {
  100831. _this.onBeforeBlurObservable.notifyObservers(_this);
  100832. var internalTexture = _this._blurTexture.getInternalTexture();
  100833. if (internalTexture) {
  100834. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  100835. }
  100836. _this.onAfterBlurObservable.notifyObservers(_this);
  100837. });
  100838. // Prevent autoClear.
  100839. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  100840. };
  100841. /**
  100842. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  100843. */
  100844. HighlightLayer.prototype.needStencil = function () {
  100845. return true;
  100846. };
  100847. /**
  100848. * Checks for the readiness of the element composing the layer.
  100849. * @param subMesh the mesh to check for
  100850. * @param useInstances specify wether or not to use instances to render the mesh
  100851. * @param emissiveTexture the associated emissive texture used to generate the glow
  100852. * @return true if ready otherwise, false
  100853. */
  100854. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  100855. var material = subMesh.getMaterial();
  100856. var mesh = subMesh.getRenderingMesh();
  100857. if (!material || !mesh || !this._meshes) {
  100858. return false;
  100859. }
  100860. var emissiveTexture = null;
  100861. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  100862. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  100863. emissiveTexture = material.emissiveTexture;
  100864. }
  100865. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  100866. };
  100867. /**
  100868. * Implementation specific of rendering the generating effect on the main canvas.
  100869. * @param effect The effect used to render through
  100870. */
  100871. HighlightLayer.prototype._internalRender = function (effect) {
  100872. // Texture
  100873. effect.setTexture("textureSampler", this._blurTexture);
  100874. // Cache
  100875. var engine = this._engine;
  100876. var previousStencilBuffer = engine.getStencilBuffer();
  100877. var previousStencilFunction = engine.getStencilFunction();
  100878. var previousStencilMask = engine.getStencilMask();
  100879. var previousStencilOperationPass = engine.getStencilOperationPass();
  100880. var previousStencilOperationFail = engine.getStencilOperationFail();
  100881. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  100882. var previousStencilReference = engine.getStencilFunctionReference();
  100883. // Stencil operations
  100884. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  100885. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  100886. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  100887. // Draw order
  100888. engine.setStencilMask(0x00);
  100889. engine.setStencilBuffer(true);
  100890. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  100891. // 2 passes inner outer
  100892. if (this.outerGlow) {
  100893. effect.setFloat("offset", 0);
  100894. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  100895. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100896. }
  100897. if (this.innerGlow) {
  100898. effect.setFloat("offset", 1);
  100899. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  100900. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100901. }
  100902. // Restore Cache
  100903. engine.setStencilFunction(previousStencilFunction);
  100904. engine.setStencilMask(previousStencilMask);
  100905. engine.setStencilBuffer(previousStencilBuffer);
  100906. engine.setStencilOperationPass(previousStencilOperationPass);
  100907. engine.setStencilOperationFail(previousStencilOperationFail);
  100908. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  100909. engine.setStencilFunctionReference(previousStencilReference);
  100910. };
  100911. /**
  100912. * Returns true if the layer contains information to display, otherwise false.
  100913. */
  100914. HighlightLayer.prototype.shouldRender = function () {
  100915. if (_super.prototype.shouldRender.call(this)) {
  100916. return this._meshes ? true : false;
  100917. }
  100918. return false;
  100919. };
  100920. /**
  100921. * Returns true if the mesh should render, otherwise false.
  100922. * @param mesh The mesh to render
  100923. * @returns true if it should render otherwise false
  100924. */
  100925. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  100926. // Excluded Mesh
  100927. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  100928. return false;
  100929. }
  100930. ;
  100931. if (!_super.prototype.hasMesh.call(this, mesh)) {
  100932. return false;
  100933. }
  100934. return true;
  100935. };
  100936. /**
  100937. * Sets the required values for both the emissive texture and and the main color.
  100938. */
  100939. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  100940. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  100941. if (highlightLayerMesh) {
  100942. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  100943. }
  100944. else {
  100945. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  100946. }
  100947. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  100948. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  100949. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  100950. }
  100951. else {
  100952. this._emissiveTextureAndColor.texture = null;
  100953. }
  100954. };
  100955. /**
  100956. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  100957. * @param mesh The mesh to exclude from the highlight layer
  100958. */
  100959. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  100960. if (!this._excludedMeshes) {
  100961. return;
  100962. }
  100963. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  100964. if (!meshExcluded) {
  100965. this._excludedMeshes[mesh.uniqueId] = {
  100966. mesh: mesh,
  100967. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  100968. mesh.getEngine().setStencilBuffer(false);
  100969. }),
  100970. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  100971. mesh.getEngine().setStencilBuffer(true);
  100972. }),
  100973. };
  100974. }
  100975. };
  100976. /**
  100977. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  100978. * @param mesh The mesh to highlight
  100979. */
  100980. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  100981. if (!this._excludedMeshes) {
  100982. return;
  100983. }
  100984. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  100985. if (meshExcluded) {
  100986. if (meshExcluded.beforeRender) {
  100987. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  100988. }
  100989. if (meshExcluded.afterRender) {
  100990. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  100991. }
  100992. }
  100993. this._excludedMeshes[mesh.uniqueId] = null;
  100994. };
  100995. /**
  100996. * Determine if a given mesh will be highlighted by the current HighlightLayer
  100997. * @param mesh mesh to test
  100998. * @returns true if the mesh will be highlighted by the current HighlightLayer
  100999. */
  101000. HighlightLayer.prototype.hasMesh = function (mesh) {
  101001. if (!this._meshes) {
  101002. return false;
  101003. }
  101004. if (!_super.prototype.hasMesh.call(this, mesh)) {
  101005. return false;
  101006. }
  101007. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  101008. };
  101009. /**
  101010. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  101011. * @param mesh The mesh to highlight
  101012. * @param color The color of the highlight
  101013. * @param glowEmissiveOnly Extract the glow from the emissive texture
  101014. */
  101015. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  101016. var _this = this;
  101017. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  101018. if (!this._meshes) {
  101019. return;
  101020. }
  101021. var meshHighlight = this._meshes[mesh.uniqueId];
  101022. if (meshHighlight) {
  101023. meshHighlight.color = color;
  101024. }
  101025. else {
  101026. this._meshes[mesh.uniqueId] = {
  101027. mesh: mesh,
  101028. color: color,
  101029. // Lambda required for capture due to Observable this context
  101030. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  101031. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  101032. _this._defaultStencilReference(mesh);
  101033. }
  101034. else {
  101035. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  101036. }
  101037. }),
  101038. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  101039. glowEmissiveOnly: glowEmissiveOnly
  101040. };
  101041. mesh.onDisposeObservable.add(function () {
  101042. _this._disposeMesh(mesh);
  101043. });
  101044. }
  101045. this._shouldRender = true;
  101046. };
  101047. /**
  101048. * Remove a mesh from the highlight layer in order to make it stop glowing.
  101049. * @param mesh The mesh to highlight
  101050. */
  101051. HighlightLayer.prototype.removeMesh = function (mesh) {
  101052. if (!this._meshes) {
  101053. return;
  101054. }
  101055. var meshHighlight = this._meshes[mesh.uniqueId];
  101056. if (meshHighlight) {
  101057. if (meshHighlight.observerHighlight) {
  101058. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  101059. }
  101060. if (meshHighlight.observerDefault) {
  101061. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  101062. }
  101063. delete this._meshes[mesh.uniqueId];
  101064. }
  101065. this._shouldRender = false;
  101066. for (var meshHighlightToCheck in this._meshes) {
  101067. if (this._meshes[meshHighlightToCheck]) {
  101068. this._shouldRender = true;
  101069. break;
  101070. }
  101071. }
  101072. };
  101073. /**
  101074. * Force the stencil to the normal expected value for none glowing parts
  101075. */
  101076. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  101077. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  101078. };
  101079. /**
  101080. * Free any resources and references associated to a mesh.
  101081. * Internal use
  101082. * @param mesh The mesh to free.
  101083. * @hidden
  101084. */
  101085. HighlightLayer.prototype._disposeMesh = function (mesh) {
  101086. this.removeMesh(mesh);
  101087. this.removeExcludedMesh(mesh);
  101088. };
  101089. /**
  101090. * Dispose the highlight layer and free resources.
  101091. */
  101092. HighlightLayer.prototype.dispose = function () {
  101093. if (this._meshes) {
  101094. // Clean mesh references
  101095. for (var id in this._meshes) {
  101096. var meshHighlight = this._meshes[id];
  101097. if (meshHighlight && meshHighlight.mesh) {
  101098. if (meshHighlight.observerHighlight) {
  101099. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  101100. }
  101101. if (meshHighlight.observerDefault) {
  101102. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  101103. }
  101104. }
  101105. }
  101106. this._meshes = null;
  101107. }
  101108. if (this._excludedMeshes) {
  101109. for (var id in this._excludedMeshes) {
  101110. var meshHighlight = this._excludedMeshes[id];
  101111. if (meshHighlight) {
  101112. if (meshHighlight.beforeRender) {
  101113. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  101114. }
  101115. if (meshHighlight.afterRender) {
  101116. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  101117. }
  101118. }
  101119. }
  101120. this._excludedMeshes = null;
  101121. }
  101122. _super.prototype.dispose.call(this);
  101123. };
  101124. /**
  101125. * Gets the class name of the effect layer
  101126. * @returns the string with the class name of the effect layer
  101127. */
  101128. HighlightLayer.prototype.getClassName = function () {
  101129. return "HighlightLayer";
  101130. };
  101131. /**
  101132. * Serializes this Highlight layer
  101133. * @returns a serialized Highlight layer object
  101134. */
  101135. HighlightLayer.prototype.serialize = function () {
  101136. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  101137. serializationObject.customType = "BABYLON.HighlightLayer";
  101138. // Highlighted meshes
  101139. serializationObject.meshes = [];
  101140. if (this._meshes) {
  101141. for (var m in this._meshes) {
  101142. var mesh = this._meshes[m];
  101143. if (mesh) {
  101144. serializationObject.meshes.push({
  101145. glowEmissiveOnly: mesh.glowEmissiveOnly,
  101146. color: mesh.color.asArray(),
  101147. meshId: mesh.mesh.id
  101148. });
  101149. }
  101150. }
  101151. }
  101152. // Excluded meshes
  101153. serializationObject.excludedMeshes = [];
  101154. if (this._excludedMeshes) {
  101155. for (var e in this._excludedMeshes) {
  101156. var excludedMesh = this._excludedMeshes[e];
  101157. if (excludedMesh) {
  101158. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  101159. }
  101160. }
  101161. }
  101162. return serializationObject;
  101163. };
  101164. /**
  101165. * Creates a Highlight layer from parsed Highlight layer data
  101166. * @param parsedHightlightLayer defines the Highlight layer data
  101167. * @param scene defines the current scene
  101168. * @param rootUrl defines the root URL containing the Highlight layer information
  101169. * @returns a parsed Highlight layer
  101170. */
  101171. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  101172. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  101173. var index;
  101174. // Excluded meshes
  101175. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  101176. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  101177. if (mesh) {
  101178. hl.addExcludedMesh(mesh);
  101179. }
  101180. }
  101181. // Included meshes
  101182. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  101183. var highlightedMesh = parsedHightlightLayer.meshes[index];
  101184. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  101185. if (mesh) {
  101186. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  101187. }
  101188. }
  101189. return hl;
  101190. };
  101191. /**
  101192. * Effect Name of the highlight layer.
  101193. */
  101194. HighlightLayer.EffectName = "HighlightLayer";
  101195. /**
  101196. * The neutral color used during the preparation of the glow effect.
  101197. * This is black by default as the blend operation is a blend operation.
  101198. */
  101199. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  101200. /**
  101201. * Stencil value used for glowing meshes.
  101202. */
  101203. HighlightLayer.GlowingMeshStencilReference = 0x02;
  101204. /**
  101205. * Stencil value used for the other meshes in the scene.
  101206. */
  101207. HighlightLayer.NormalMeshStencilReference = 0x01;
  101208. __decorate([
  101209. BABYLON.serialize()
  101210. ], HighlightLayer.prototype, "innerGlow", void 0);
  101211. __decorate([
  101212. BABYLON.serialize()
  101213. ], HighlightLayer.prototype, "outerGlow", void 0);
  101214. __decorate([
  101215. BABYLON.serialize()
  101216. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  101217. __decorate([
  101218. BABYLON.serialize()
  101219. ], HighlightLayer.prototype, "blurVerticalSize", null);
  101220. __decorate([
  101221. BABYLON.serialize("options")
  101222. ], HighlightLayer.prototype, "_options", void 0);
  101223. return HighlightLayer;
  101224. }(BABYLON.EffectLayer));
  101225. BABYLON.HighlightLayer = HighlightLayer;
  101226. })(BABYLON || (BABYLON = {}));
  101227. //# sourceMappingURL=babylon.highlightLayer.js.map
  101228. var BABYLON;
  101229. (function (BABYLON) {
  101230. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  101231. for (var index = 0; index < this.effectLayers.length; index++) {
  101232. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  101233. return this.effectLayers[index];
  101234. }
  101235. }
  101236. return null;
  101237. };
  101238. /**
  101239. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  101240. *
  101241. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  101242. * glowy meshes to your scene.
  101243. *
  101244. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  101245. */
  101246. var GlowLayer = /** @class */ (function (_super) {
  101247. __extends(GlowLayer, _super);
  101248. /**
  101249. * Instantiates a new glow Layer and references it to the scene.
  101250. * @param name The name of the layer
  101251. * @param scene The scene to use the layer in
  101252. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  101253. */
  101254. function GlowLayer(name, scene, options) {
  101255. var _this = _super.call(this, name, scene) || this;
  101256. _this._intensity = 1.0;
  101257. _this._includedOnlyMeshes = [];
  101258. _this._excludedMeshes = [];
  101259. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  101260. // Adapt options
  101261. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  101262. // Initialize the layer
  101263. _this._init({
  101264. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  101265. camera: _this._options.camera,
  101266. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  101267. mainTextureRatio: _this._options.mainTextureRatio,
  101268. renderingGroupId: _this._options.renderingGroupId
  101269. });
  101270. return _this;
  101271. }
  101272. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  101273. /**
  101274. * Gets the kernel size of the blur.
  101275. */
  101276. get: function () {
  101277. return this._horizontalBlurPostprocess1.kernel;
  101278. },
  101279. /**
  101280. * Sets the kernel size of the blur.
  101281. */
  101282. set: function (value) {
  101283. this._horizontalBlurPostprocess1.kernel = value;
  101284. this._verticalBlurPostprocess1.kernel = value;
  101285. this._horizontalBlurPostprocess2.kernel = value;
  101286. this._verticalBlurPostprocess2.kernel = value;
  101287. },
  101288. enumerable: true,
  101289. configurable: true
  101290. });
  101291. Object.defineProperty(GlowLayer.prototype, "intensity", {
  101292. /**
  101293. * Gets the glow intensity.
  101294. */
  101295. get: function () {
  101296. return this._intensity;
  101297. },
  101298. /**
  101299. * Sets the glow intensity.
  101300. */
  101301. set: function (value) {
  101302. this._intensity = value;
  101303. },
  101304. enumerable: true,
  101305. configurable: true
  101306. });
  101307. /**
  101308. * Get the effect name of the layer.
  101309. * @return The effect name
  101310. */
  101311. GlowLayer.prototype.getEffectName = function () {
  101312. return GlowLayer.EffectName;
  101313. };
  101314. /**
  101315. * Create the merge effect. This is the shader use to blit the information back
  101316. * to the main canvas at the end of the scene rendering.
  101317. */
  101318. GlowLayer.prototype._createMergeEffect = function () {
  101319. // Effect
  101320. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  101321. };
  101322. /**
  101323. * Creates the render target textures and post processes used in the glow layer.
  101324. */
  101325. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  101326. var _this = this;
  101327. var blurTextureWidth = this._mainTextureDesiredSize.width;
  101328. var blurTextureHeight = this._mainTextureDesiredSize.height;
  101329. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  101330. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  101331. var textureType = 0;
  101332. if (this._engine.getCaps().textureHalfFloatRender) {
  101333. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  101334. }
  101335. else {
  101336. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  101337. }
  101338. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  101339. width: blurTextureWidth,
  101340. height: blurTextureHeight
  101341. }, this._scene, false, true, textureType);
  101342. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101343. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101344. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  101345. this._blurTexture1.renderParticles = false;
  101346. this._blurTexture1.ignoreCameraViewport = true;
  101347. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  101348. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  101349. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  101350. width: blurTextureWidth2,
  101351. height: blurTextureHeight2
  101352. }, this._scene, false, true, textureType);
  101353. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101354. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101355. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  101356. this._blurTexture2.renderParticles = false;
  101357. this._blurTexture2.ignoreCameraViewport = true;
  101358. this._textures = [this._blurTexture1, this._blurTexture2];
  101359. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  101360. width: blurTextureWidth,
  101361. height: blurTextureHeight
  101362. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101363. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  101364. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  101365. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  101366. effect.setTexture("textureSampler", _this._mainTexture);
  101367. });
  101368. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  101369. width: blurTextureWidth,
  101370. height: blurTextureHeight
  101371. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101372. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  101373. width: blurTextureWidth2,
  101374. height: blurTextureHeight2
  101375. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101376. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  101377. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  101378. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  101379. effect.setTexture("textureSampler", _this._blurTexture1);
  101380. });
  101381. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  101382. width: blurTextureWidth2,
  101383. height: blurTextureHeight2
  101384. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101385. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  101386. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  101387. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  101388. this._mainTexture.samples = this._options.mainTextureSamples;
  101389. this._mainTexture.onAfterUnbindObservable.add(function () {
  101390. var internalTexture = _this._blurTexture1.getInternalTexture();
  101391. if (internalTexture) {
  101392. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  101393. internalTexture = _this._blurTexture2.getInternalTexture();
  101394. if (internalTexture) {
  101395. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  101396. }
  101397. }
  101398. });
  101399. // Prevent autoClear.
  101400. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  101401. };
  101402. /**
  101403. * Checks for the readiness of the element composing the layer.
  101404. * @param subMesh the mesh to check for
  101405. * @param useInstances specify wether or not to use instances to render the mesh
  101406. * @param emissiveTexture the associated emissive texture used to generate the glow
  101407. * @return true if ready otherwise, false
  101408. */
  101409. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  101410. var material = subMesh.getMaterial();
  101411. var mesh = subMesh.getRenderingMesh();
  101412. if (!material || !mesh) {
  101413. return false;
  101414. }
  101415. var emissiveTexture = material.emissiveTexture;
  101416. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  101417. };
  101418. /**
  101419. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  101420. */
  101421. GlowLayer.prototype.needStencil = function () {
  101422. return false;
  101423. };
  101424. /**
  101425. * Implementation specific of rendering the generating effect on the main canvas.
  101426. * @param effect The effect used to render through
  101427. */
  101428. GlowLayer.prototype._internalRender = function (effect) {
  101429. // Texture
  101430. effect.setTexture("textureSampler", this._blurTexture1);
  101431. effect.setTexture("textureSampler2", this._blurTexture2);
  101432. effect.setFloat("offset", this._intensity);
  101433. // Cache
  101434. var engine = this._engine;
  101435. var previousStencilBuffer = engine.getStencilBuffer();
  101436. // Draw order
  101437. engine.setStencilBuffer(false);
  101438. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  101439. // Draw order
  101440. engine.setStencilBuffer(previousStencilBuffer);
  101441. };
  101442. /**
  101443. * Sets the required values for both the emissive texture and and the main color.
  101444. */
  101445. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  101446. var textureLevel = 1.0;
  101447. if (this.customEmissiveTextureSelector) {
  101448. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  101449. }
  101450. else {
  101451. if (material) {
  101452. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  101453. if (this._emissiveTextureAndColor.texture) {
  101454. textureLevel = this._emissiveTextureAndColor.texture.level;
  101455. }
  101456. }
  101457. else {
  101458. this._emissiveTextureAndColor.texture = null;
  101459. }
  101460. }
  101461. if (this.customEmissiveColorSelector) {
  101462. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  101463. }
  101464. else {
  101465. if (material.emissiveColor) {
  101466. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  101467. }
  101468. else {
  101469. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  101470. }
  101471. }
  101472. };
  101473. /**
  101474. * Returns true if the mesh should render, otherwise false.
  101475. * @param mesh The mesh to render
  101476. * @returns true if it should render otherwise false
  101477. */
  101478. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  101479. return this.hasMesh(mesh);
  101480. };
  101481. /**
  101482. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  101483. * @param mesh The mesh to exclude from the glow layer
  101484. */
  101485. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  101486. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  101487. this._excludedMeshes.push(mesh.uniqueId);
  101488. }
  101489. };
  101490. /**
  101491. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  101492. * @param mesh The mesh to remove
  101493. */
  101494. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  101495. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  101496. if (index !== -1) {
  101497. this._excludedMeshes.splice(index, 1);
  101498. }
  101499. };
  101500. /**
  101501. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  101502. * @param mesh The mesh to include in the glow layer
  101503. */
  101504. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  101505. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  101506. this._includedOnlyMeshes.push(mesh.uniqueId);
  101507. }
  101508. };
  101509. /**
  101510. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  101511. * @param mesh The mesh to remove
  101512. */
  101513. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  101514. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  101515. if (index !== -1) {
  101516. this._includedOnlyMeshes.splice(index, 1);
  101517. }
  101518. };
  101519. /**
  101520. * Determine if a given mesh will be used in the glow layer
  101521. * @param mesh The mesh to test
  101522. * @returns true if the mesh will be highlighted by the current glow layer
  101523. */
  101524. GlowLayer.prototype.hasMesh = function (mesh) {
  101525. if (!_super.prototype.hasMesh.call(this, mesh)) {
  101526. return false;
  101527. }
  101528. // Included Mesh
  101529. if (this._includedOnlyMeshes.length) {
  101530. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  101531. }
  101532. ;
  101533. // Excluded Mesh
  101534. if (this._excludedMeshes.length) {
  101535. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  101536. }
  101537. ;
  101538. return true;
  101539. };
  101540. /**
  101541. * Free any resources and references associated to a mesh.
  101542. * Internal use
  101543. * @param mesh The mesh to free.
  101544. * @hidden
  101545. */
  101546. GlowLayer.prototype._disposeMesh = function (mesh) {
  101547. this.removeIncludedOnlyMesh(mesh);
  101548. this.removeExcludedMesh(mesh);
  101549. };
  101550. /**
  101551. * Gets the class name of the effect layer
  101552. * @returns the string with the class name of the effect layer
  101553. */
  101554. GlowLayer.prototype.getClassName = function () {
  101555. return "GlowLayer";
  101556. };
  101557. /**
  101558. * Serializes this glow layer
  101559. * @returns a serialized glow layer object
  101560. */
  101561. GlowLayer.prototype.serialize = function () {
  101562. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  101563. serializationObject.customType = "BABYLON.GlowLayer";
  101564. var index;
  101565. // Included meshes
  101566. serializationObject.includedMeshes = [];
  101567. if (this._includedOnlyMeshes.length) {
  101568. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  101569. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  101570. if (mesh) {
  101571. serializationObject.includedMeshes.push(mesh.id);
  101572. }
  101573. }
  101574. }
  101575. // Excluded meshes
  101576. serializationObject.excludedMeshes = [];
  101577. if (this._excludedMeshes.length) {
  101578. for (index = 0; index < this._excludedMeshes.length; index++) {
  101579. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  101580. if (mesh) {
  101581. serializationObject.excludedMeshes.push(mesh.id);
  101582. }
  101583. }
  101584. }
  101585. return serializationObject;
  101586. };
  101587. /**
  101588. * Creates a Glow Layer from parsed glow layer data
  101589. * @param parsedGlowLayer defines glow layer data
  101590. * @param scene defines the current scene
  101591. * @param rootUrl defines the root URL containing the glow layer information
  101592. * @returns a parsed Glow Layer
  101593. */
  101594. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  101595. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  101596. var index;
  101597. // Excluded meshes
  101598. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  101599. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  101600. if (mesh) {
  101601. gl.addExcludedMesh(mesh);
  101602. }
  101603. }
  101604. // Included meshes
  101605. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  101606. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  101607. if (mesh) {
  101608. gl.addIncludedOnlyMesh(mesh);
  101609. }
  101610. }
  101611. return gl;
  101612. };
  101613. /**
  101614. * Effect Name of the layer.
  101615. */
  101616. GlowLayer.EffectName = "GlowLayer";
  101617. /**
  101618. * The default blur kernel size used for the glow.
  101619. */
  101620. GlowLayer.DefaultBlurKernelSize = 32;
  101621. /**
  101622. * The default texture size ratio used for the glow.
  101623. */
  101624. GlowLayer.DefaultTextureRatio = 0.5;
  101625. __decorate([
  101626. BABYLON.serialize()
  101627. ], GlowLayer.prototype, "blurKernelSize", null);
  101628. __decorate([
  101629. BABYLON.serialize()
  101630. ], GlowLayer.prototype, "intensity", null);
  101631. __decorate([
  101632. BABYLON.serialize("options")
  101633. ], GlowLayer.prototype, "_options", void 0);
  101634. return GlowLayer;
  101635. }(BABYLON.EffectLayer));
  101636. BABYLON.GlowLayer = GlowLayer;
  101637. })(BABYLON || (BABYLON = {}));
  101638. //# sourceMappingURL=babylon.glowLayer.js.map
  101639. var BABYLON;
  101640. (function (BABYLON) {
  101641. /**
  101642. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  101643. */
  101644. var AssetTaskState;
  101645. (function (AssetTaskState) {
  101646. /**
  101647. * Initialization
  101648. */
  101649. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  101650. /**
  101651. * Running
  101652. */
  101653. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  101654. /**
  101655. * Done
  101656. */
  101657. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  101658. /**
  101659. * Error
  101660. */
  101661. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  101662. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  101663. /**
  101664. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  101665. */
  101666. var AbstractAssetTask = /** @class */ (function () {
  101667. /**
  101668. * Creates a new {BABYLON.AssetsManager}
  101669. * @param name defines the name of the task
  101670. */
  101671. function AbstractAssetTask(
  101672. /**
  101673. * Task name
  101674. */ name) {
  101675. this.name = name;
  101676. this._isCompleted = false;
  101677. this._taskState = AssetTaskState.INIT;
  101678. }
  101679. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  101680. /**
  101681. * Get if the task is completed
  101682. */
  101683. get: function () {
  101684. return this._isCompleted;
  101685. },
  101686. enumerable: true,
  101687. configurable: true
  101688. });
  101689. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  101690. /**
  101691. * Gets the current state of the task
  101692. */
  101693. get: function () {
  101694. return this._taskState;
  101695. },
  101696. enumerable: true,
  101697. configurable: true
  101698. });
  101699. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  101700. /**
  101701. * Gets the current error object (if task is in error)
  101702. */
  101703. get: function () {
  101704. return this._errorObject;
  101705. },
  101706. enumerable: true,
  101707. configurable: true
  101708. });
  101709. /**
  101710. * Internal only
  101711. * @hidden
  101712. */
  101713. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  101714. if (this._errorObject) {
  101715. return;
  101716. }
  101717. this._errorObject = {
  101718. message: message,
  101719. exception: exception
  101720. };
  101721. };
  101722. /**
  101723. * Execute the current task
  101724. * @param scene defines the scene where you want your assets to be loaded
  101725. * @param onSuccess is a callback called when the task is successfully executed
  101726. * @param onError is a callback called if an error occurs
  101727. */
  101728. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  101729. var _this = this;
  101730. this._taskState = AssetTaskState.RUNNING;
  101731. this.runTask(scene, function () {
  101732. _this.onDoneCallback(onSuccess, onError);
  101733. }, function (msg, exception) {
  101734. _this.onErrorCallback(onError, msg, exception);
  101735. });
  101736. };
  101737. /**
  101738. * Execute the current task
  101739. * @param scene defines the scene where you want your assets to be loaded
  101740. * @param onSuccess is a callback called when the task is successfully executed
  101741. * @param onError is a callback called if an error occurs
  101742. */
  101743. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101744. throw new Error("runTask is not implemented");
  101745. };
  101746. /**
  101747. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  101748. * This can be used with failed tasks that have the reason for failure fixed.
  101749. */
  101750. AbstractAssetTask.prototype.reset = function () {
  101751. this._taskState = AssetTaskState.INIT;
  101752. };
  101753. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  101754. this._taskState = AssetTaskState.ERROR;
  101755. this._errorObject = {
  101756. message: message,
  101757. exception: exception
  101758. };
  101759. if (this.onError) {
  101760. this.onError(this, message, exception);
  101761. }
  101762. onError();
  101763. };
  101764. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  101765. try {
  101766. this._taskState = AssetTaskState.DONE;
  101767. this._isCompleted = true;
  101768. if (this.onSuccess) {
  101769. this.onSuccess(this);
  101770. }
  101771. onSuccess();
  101772. }
  101773. catch (e) {
  101774. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  101775. }
  101776. };
  101777. return AbstractAssetTask;
  101778. }());
  101779. BABYLON.AbstractAssetTask = AbstractAssetTask;
  101780. /**
  101781. * Class used to share progress information about assets loading
  101782. */
  101783. var AssetsProgressEvent = /** @class */ (function () {
  101784. /**
  101785. * Creates a {BABYLON.AssetsProgressEvent}
  101786. * @param remainingCount defines the number of remaining tasks to process
  101787. * @param totalCount defines the total number of tasks
  101788. * @param task defines the task that was just processed
  101789. */
  101790. function AssetsProgressEvent(remainingCount, totalCount, task) {
  101791. this.remainingCount = remainingCount;
  101792. this.totalCount = totalCount;
  101793. this.task = task;
  101794. }
  101795. return AssetsProgressEvent;
  101796. }());
  101797. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  101798. /**
  101799. * Define a task used by {BABYLON.AssetsManager} to load meshes
  101800. */
  101801. var MeshAssetTask = /** @class */ (function (_super) {
  101802. __extends(MeshAssetTask, _super);
  101803. /**
  101804. * Creates a new {BABYLON.MeshAssetTask}
  101805. * @param name defines the name of the task
  101806. * @param meshesNames defines the list of mesh's names you want to load
  101807. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  101808. * @param sceneFilename defines the filename of the scene to load from
  101809. */
  101810. function MeshAssetTask(
  101811. /**
  101812. * Defines the name of the task
  101813. */
  101814. name,
  101815. /**
  101816. * Defines the list of mesh's names you want to load
  101817. */
  101818. meshesNames,
  101819. /**
  101820. * Defines the root url to use as a base to load your meshes and associated resources
  101821. */
  101822. rootUrl,
  101823. /**
  101824. * Defines the filename of the scene to load from
  101825. */
  101826. sceneFilename) {
  101827. var _this = _super.call(this, name) || this;
  101828. _this.name = name;
  101829. _this.meshesNames = meshesNames;
  101830. _this.rootUrl = rootUrl;
  101831. _this.sceneFilename = sceneFilename;
  101832. return _this;
  101833. }
  101834. /**
  101835. * Execute the current task
  101836. * @param scene defines the scene where you want your assets to be loaded
  101837. * @param onSuccess is a callback called when the task is successfully executed
  101838. * @param onError is a callback called if an error occurs
  101839. */
  101840. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101841. var _this = this;
  101842. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  101843. _this.loadedMeshes = meshes;
  101844. _this.loadedParticleSystems = particleSystems;
  101845. _this.loadedSkeletons = skeletons;
  101846. onSuccess();
  101847. }, null, function (scene, message, exception) {
  101848. onError(message, exception);
  101849. });
  101850. };
  101851. return MeshAssetTask;
  101852. }(AbstractAssetTask));
  101853. BABYLON.MeshAssetTask = MeshAssetTask;
  101854. /**
  101855. * Define a task used by {BABYLON.AssetsManager} to load text content
  101856. */
  101857. var TextFileAssetTask = /** @class */ (function (_super) {
  101858. __extends(TextFileAssetTask, _super);
  101859. /**
  101860. * Creates a new TextFileAssetTask object
  101861. * @param name defines the name of the task
  101862. * @param url defines the location of the file to load
  101863. */
  101864. function TextFileAssetTask(
  101865. /**
  101866. * Defines the name of the task
  101867. */
  101868. name,
  101869. /**
  101870. * Defines the location of the file to load
  101871. */
  101872. url) {
  101873. var _this = _super.call(this, name) || this;
  101874. _this.name = name;
  101875. _this.url = url;
  101876. return _this;
  101877. }
  101878. /**
  101879. * Execute the current task
  101880. * @param scene defines the scene where you want your assets to be loaded
  101881. * @param onSuccess is a callback called when the task is successfully executed
  101882. * @param onError is a callback called if an error occurs
  101883. */
  101884. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101885. var _this = this;
  101886. scene._loadFile(this.url, function (data) {
  101887. _this.text = data;
  101888. onSuccess();
  101889. }, undefined, false, false, function (request, exception) {
  101890. if (request) {
  101891. onError(request.status + " " + request.statusText, exception);
  101892. }
  101893. });
  101894. };
  101895. return TextFileAssetTask;
  101896. }(AbstractAssetTask));
  101897. BABYLON.TextFileAssetTask = TextFileAssetTask;
  101898. /**
  101899. * Define a task used by {BABYLON.AssetsManager} to load binary data
  101900. */
  101901. var BinaryFileAssetTask = /** @class */ (function (_super) {
  101902. __extends(BinaryFileAssetTask, _super);
  101903. /**
  101904. * Creates a new BinaryFileAssetTask object
  101905. * @param name defines the name of the new task
  101906. * @param url defines the location of the file to load
  101907. */
  101908. function BinaryFileAssetTask(
  101909. /**
  101910. * Defines the name of the task
  101911. */
  101912. name,
  101913. /**
  101914. * Defines the location of the file to load
  101915. */
  101916. url) {
  101917. var _this = _super.call(this, name) || this;
  101918. _this.name = name;
  101919. _this.url = url;
  101920. return _this;
  101921. }
  101922. /**
  101923. * Execute the current task
  101924. * @param scene defines the scene where you want your assets to be loaded
  101925. * @param onSuccess is a callback called when the task is successfully executed
  101926. * @param onError is a callback called if an error occurs
  101927. */
  101928. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101929. var _this = this;
  101930. scene._loadFile(this.url, function (data) {
  101931. _this.data = data;
  101932. onSuccess();
  101933. }, undefined, true, true, function (request, exception) {
  101934. if (request) {
  101935. onError(request.status + " " + request.statusText, exception);
  101936. }
  101937. });
  101938. };
  101939. return BinaryFileAssetTask;
  101940. }(AbstractAssetTask));
  101941. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  101942. /**
  101943. * Define a task used by {BABYLON.AssetsManager} to load images
  101944. */
  101945. var ImageAssetTask = /** @class */ (function (_super) {
  101946. __extends(ImageAssetTask, _super);
  101947. /**
  101948. * Creates a new ImageAssetTask
  101949. * @param name defines the name of the task
  101950. * @param url defines the location of the image to load
  101951. */
  101952. function ImageAssetTask(
  101953. /**
  101954. * Defines the name of the task
  101955. */
  101956. name,
  101957. /**
  101958. * Defines the location of the image to load
  101959. */
  101960. url) {
  101961. var _this = _super.call(this, name) || this;
  101962. _this.name = name;
  101963. _this.url = url;
  101964. return _this;
  101965. }
  101966. /**
  101967. * Execute the current task
  101968. * @param scene defines the scene where you want your assets to be loaded
  101969. * @param onSuccess is a callback called when the task is successfully executed
  101970. * @param onError is a callback called if an error occurs
  101971. */
  101972. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101973. var _this = this;
  101974. var img = new Image();
  101975. BABYLON.Tools.SetCorsBehavior(this.url, img);
  101976. img.onload = function () {
  101977. _this.image = img;
  101978. onSuccess();
  101979. };
  101980. img.onerror = function (err) {
  101981. onError("Error loading image", err);
  101982. };
  101983. img.src = this.url;
  101984. };
  101985. return ImageAssetTask;
  101986. }(AbstractAssetTask));
  101987. BABYLON.ImageAssetTask = ImageAssetTask;
  101988. /**
  101989. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  101990. */
  101991. var TextureAssetTask = /** @class */ (function (_super) {
  101992. __extends(TextureAssetTask, _super);
  101993. /**
  101994. * Creates a new TextureAssetTask object
  101995. * @param name defines the name of the task
  101996. * @param url defines the location of the file to load
  101997. * @param noMipmap defines if mipmap should not be generated (default is false)
  101998. * @param invertY defines if texture must be inverted on Y axis (default is false)
  101999. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  102000. */
  102001. function TextureAssetTask(
  102002. /**
  102003. * Defines the name of the task
  102004. */
  102005. name,
  102006. /**
  102007. * Defines the location of the file to load
  102008. */
  102009. url,
  102010. /**
  102011. * Defines if mipmap should not be generated (default is false)
  102012. */
  102013. noMipmap,
  102014. /**
  102015. * Defines if texture must be inverted on Y axis (default is false)
  102016. */
  102017. invertY,
  102018. /**
  102019. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  102020. */
  102021. samplingMode) {
  102022. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  102023. var _this = _super.call(this, name) || this;
  102024. _this.name = name;
  102025. _this.url = url;
  102026. _this.noMipmap = noMipmap;
  102027. _this.invertY = invertY;
  102028. _this.samplingMode = samplingMode;
  102029. return _this;
  102030. }
  102031. /**
  102032. * Execute the current task
  102033. * @param scene defines the scene where you want your assets to be loaded
  102034. * @param onSuccess is a callback called when the task is successfully executed
  102035. * @param onError is a callback called if an error occurs
  102036. */
  102037. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  102038. var onload = function () {
  102039. onSuccess();
  102040. };
  102041. var onerror = function (message, exception) {
  102042. onError(message, exception);
  102043. };
  102044. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  102045. };
  102046. return TextureAssetTask;
  102047. }(AbstractAssetTask));
  102048. BABYLON.TextureAssetTask = TextureAssetTask;
  102049. /**
  102050. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  102051. */
  102052. var CubeTextureAssetTask = /** @class */ (function (_super) {
  102053. __extends(CubeTextureAssetTask, _super);
  102054. /**
  102055. * Creates a new CubeTextureAssetTask
  102056. * @param name defines the name of the task
  102057. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  102058. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  102059. * @param noMipmap defines if mipmaps should not be generated (default is false)
  102060. * @param files defines the explicit list of files (undefined by default)
  102061. */
  102062. function CubeTextureAssetTask(
  102063. /**
  102064. * Defines the name of the task
  102065. */
  102066. name,
  102067. /**
  102068. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  102069. */
  102070. url,
  102071. /**
  102072. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  102073. */
  102074. extensions,
  102075. /**
  102076. * Defines if mipmaps should not be generated (default is false)
  102077. */
  102078. noMipmap,
  102079. /**
  102080. * Defines the explicit list of files (undefined by default)
  102081. */
  102082. files) {
  102083. var _this = _super.call(this, name) || this;
  102084. _this.name = name;
  102085. _this.url = url;
  102086. _this.extensions = extensions;
  102087. _this.noMipmap = noMipmap;
  102088. _this.files = files;
  102089. return _this;
  102090. }
  102091. /**
  102092. * Execute the current task
  102093. * @param scene defines the scene where you want your assets to be loaded
  102094. * @param onSuccess is a callback called when the task is successfully executed
  102095. * @param onError is a callback called if an error occurs
  102096. */
  102097. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  102098. var onload = function () {
  102099. onSuccess();
  102100. };
  102101. var onerror = function (message, exception) {
  102102. onError(message, exception);
  102103. };
  102104. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  102105. };
  102106. return CubeTextureAssetTask;
  102107. }(AbstractAssetTask));
  102108. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  102109. /**
  102110. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  102111. */
  102112. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  102113. __extends(HDRCubeTextureAssetTask, _super);
  102114. /**
  102115. * Creates a new HDRCubeTextureAssetTask object
  102116. * @param name defines the name of the task
  102117. * @param url defines the location of the file to load
  102118. * @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.
  102119. * @param noMipmap defines if mipmaps should not be generated (default is false)
  102120. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  102121. * @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)
  102122. * @param reserved Internal use only
  102123. */
  102124. function HDRCubeTextureAssetTask(
  102125. /**
  102126. * Defines the name of the task
  102127. */
  102128. name,
  102129. /**
  102130. * Defines the location of the file to load
  102131. */
  102132. url,
  102133. /**
  102134. * Defines the desired size (the more it increases the longer the generation will be)
  102135. */
  102136. size,
  102137. /**
  102138. * Defines if mipmaps should not be generated (default is false)
  102139. */
  102140. noMipmap,
  102141. /**
  102142. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  102143. */
  102144. generateHarmonics,
  102145. /**
  102146. * 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)
  102147. */
  102148. gammaSpace,
  102149. /**
  102150. * Internal Use Only
  102151. */
  102152. reserved) {
  102153. if (noMipmap === void 0) { noMipmap = false; }
  102154. if (generateHarmonics === void 0) { generateHarmonics = true; }
  102155. if (gammaSpace === void 0) { gammaSpace = false; }
  102156. if (reserved === void 0) { reserved = false; }
  102157. var _this = _super.call(this, name) || this;
  102158. _this.name = name;
  102159. _this.url = url;
  102160. _this.size = size;
  102161. _this.noMipmap = noMipmap;
  102162. _this.generateHarmonics = generateHarmonics;
  102163. _this.gammaSpace = gammaSpace;
  102164. _this.reserved = reserved;
  102165. return _this;
  102166. }
  102167. /**
  102168. * Execute the current task
  102169. * @param scene defines the scene where you want your assets to be loaded
  102170. * @param onSuccess is a callback called when the task is successfully executed
  102171. * @param onError is a callback called if an error occurs
  102172. */
  102173. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  102174. var onload = function () {
  102175. onSuccess();
  102176. };
  102177. var onerror = function (message, exception) {
  102178. onError(message, exception);
  102179. };
  102180. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  102181. };
  102182. return HDRCubeTextureAssetTask;
  102183. }(AbstractAssetTask));
  102184. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  102185. /**
  102186. * This class can be used to easily import assets into a scene
  102187. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  102188. */
  102189. var AssetsManager = /** @class */ (function () {
  102190. /**
  102191. * Creates a new AssetsManager
  102192. * @param scene defines the scene to work on
  102193. */
  102194. function AssetsManager(scene) {
  102195. this._isLoading = false;
  102196. this._tasks = new Array();
  102197. this._waitingTasksCount = 0;
  102198. this._totalTasksCount = 0;
  102199. /**
  102200. * Observable called when all tasks are processed
  102201. */
  102202. this.onTaskSuccessObservable = new BABYLON.Observable();
  102203. /**
  102204. * Observable called when a task had an error
  102205. */
  102206. this.onTaskErrorObservable = new BABYLON.Observable();
  102207. /**
  102208. * Observable called when a task is successful
  102209. */
  102210. this.onTasksDoneObservable = new BABYLON.Observable();
  102211. /**
  102212. * Observable called when a task is done (whatever the result is)
  102213. */
  102214. this.onProgressObservable = new BABYLON.Observable();
  102215. /**
  102216. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  102217. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  102218. */
  102219. this.useDefaultLoadingScreen = true;
  102220. this._scene = scene;
  102221. }
  102222. /**
  102223. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  102224. * @param taskName defines the name of the new task
  102225. * @param meshesNames defines the name of meshes to load
  102226. * @param rootUrl defines the root url to use to locate files
  102227. * @param sceneFilename defines the filename of the scene file
  102228. * @returns a new {BABYLON.MeshAssetTask} object
  102229. */
  102230. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  102231. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  102232. this._tasks.push(task);
  102233. return task;
  102234. };
  102235. /**
  102236. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  102237. * @param taskName defines the name of the new task
  102238. * @param url defines the url of the file to load
  102239. * @returns a new {BABYLON.TextFileAssetTask} object
  102240. */
  102241. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  102242. var task = new TextFileAssetTask(taskName, url);
  102243. this._tasks.push(task);
  102244. return task;
  102245. };
  102246. /**
  102247. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  102248. * @param taskName defines the name of the new task
  102249. * @param url defines the url of the file to load
  102250. * @returns a new {BABYLON.BinaryFileAssetTask} object
  102251. */
  102252. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  102253. var task = new BinaryFileAssetTask(taskName, url);
  102254. this._tasks.push(task);
  102255. return task;
  102256. };
  102257. /**
  102258. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  102259. * @param taskName defines the name of the new task
  102260. * @param url defines the url of the file to load
  102261. * @returns a new {BABYLON.ImageAssetTask} object
  102262. */
  102263. AssetsManager.prototype.addImageTask = function (taskName, url) {
  102264. var task = new ImageAssetTask(taskName, url);
  102265. this._tasks.push(task);
  102266. return task;
  102267. };
  102268. /**
  102269. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  102270. * @param taskName defines the name of the new task
  102271. * @param url defines the url of the file to load
  102272. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  102273. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  102274. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  102275. * @returns a new {BABYLON.TextureAssetTask} object
  102276. */
  102277. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  102278. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  102279. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  102280. this._tasks.push(task);
  102281. return task;
  102282. };
  102283. /**
  102284. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  102285. * @param taskName defines the name of the new task
  102286. * @param url defines the url of the file to load
  102287. * @param extensions defines the extension to use to load the cube map (can be null)
  102288. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  102289. * @param files defines the list of files to load (can be null)
  102290. * @returns a new {BABYLON.CubeTextureAssetTask} object
  102291. */
  102292. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  102293. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  102294. this._tasks.push(task);
  102295. return task;
  102296. };
  102297. /**
  102298. *
  102299. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  102300. * @param taskName defines the name of the new task
  102301. * @param url defines the url of the file to load
  102302. * @param size defines the size you want for the cubemap (can be null)
  102303. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  102304. * @param generateHarmonics defines if you want to automatically generate (true by default)
  102305. * @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)
  102306. * @param reserved Internal use only
  102307. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  102308. */
  102309. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  102310. if (noMipmap === void 0) { noMipmap = false; }
  102311. if (generateHarmonics === void 0) { generateHarmonics = true; }
  102312. if (gammaSpace === void 0) { gammaSpace = false; }
  102313. if (reserved === void 0) { reserved = false; }
  102314. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  102315. this._tasks.push(task);
  102316. return task;
  102317. };
  102318. /**
  102319. * Remove a task from the assets manager.
  102320. * @param task the task to remove
  102321. */
  102322. AssetsManager.prototype.removeTask = function (task) {
  102323. var index = this._tasks.indexOf(task);
  102324. if (index > -1) {
  102325. this._tasks.splice(index, 1);
  102326. }
  102327. };
  102328. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  102329. this._waitingTasksCount--;
  102330. try {
  102331. if (this.onProgress) {
  102332. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  102333. }
  102334. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  102335. }
  102336. catch (e) {
  102337. BABYLON.Tools.Error("Error running progress callbacks.");
  102338. console.log(e);
  102339. }
  102340. if (this._waitingTasksCount === 0) {
  102341. try {
  102342. if (this.onFinish) {
  102343. this.onFinish(this._tasks);
  102344. }
  102345. // Let's remove successfull tasks
  102346. var currentTasks = this._tasks.slice();
  102347. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  102348. var task = currentTasks_1[_i];
  102349. if (task.taskState === AssetTaskState.DONE) {
  102350. var index = this._tasks.indexOf(task);
  102351. if (index > -1) {
  102352. this._tasks.splice(index, 1);
  102353. }
  102354. }
  102355. }
  102356. this.onTasksDoneObservable.notifyObservers(this._tasks);
  102357. }
  102358. catch (e) {
  102359. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  102360. console.log(e);
  102361. }
  102362. this._isLoading = false;
  102363. this._scene.getEngine().hideLoadingUI();
  102364. }
  102365. };
  102366. AssetsManager.prototype._runTask = function (task) {
  102367. var _this = this;
  102368. var done = function () {
  102369. try {
  102370. if (_this.onTaskSuccess) {
  102371. _this.onTaskSuccess(task);
  102372. }
  102373. _this.onTaskSuccessObservable.notifyObservers(task);
  102374. _this._decreaseWaitingTasksCount(task);
  102375. }
  102376. catch (e) {
  102377. error("Error executing task success callbacks", e);
  102378. }
  102379. };
  102380. var error = function (message, exception) {
  102381. task._setErrorObject(message, exception);
  102382. if (_this.onTaskError) {
  102383. _this.onTaskError(task);
  102384. }
  102385. _this.onTaskErrorObservable.notifyObservers(task);
  102386. _this._decreaseWaitingTasksCount(task);
  102387. };
  102388. task.run(this._scene, done, error);
  102389. };
  102390. /**
  102391. * Reset the {BABYLON.AssetsManager} and remove all tasks
  102392. * @return the current instance of the {BABYLON.AssetsManager}
  102393. */
  102394. AssetsManager.prototype.reset = function () {
  102395. this._isLoading = false;
  102396. this._tasks = new Array();
  102397. return this;
  102398. };
  102399. /**
  102400. * Start the loading process
  102401. * @return the current instance of the {BABYLON.AssetsManager}
  102402. */
  102403. AssetsManager.prototype.load = function () {
  102404. if (this._isLoading) {
  102405. return this;
  102406. }
  102407. this._isLoading = true;
  102408. this._waitingTasksCount = this._tasks.length;
  102409. this._totalTasksCount = this._tasks.length;
  102410. if (this._waitingTasksCount === 0) {
  102411. this._isLoading = false;
  102412. if (this.onFinish) {
  102413. this.onFinish(this._tasks);
  102414. }
  102415. this.onTasksDoneObservable.notifyObservers(this._tasks);
  102416. return this;
  102417. }
  102418. if (this.useDefaultLoadingScreen) {
  102419. this._scene.getEngine().displayLoadingUI();
  102420. }
  102421. for (var index = 0; index < this._tasks.length; index++) {
  102422. var task = this._tasks[index];
  102423. if (task.taskState === AssetTaskState.INIT) {
  102424. this._runTask(task);
  102425. }
  102426. }
  102427. return this;
  102428. };
  102429. return AssetsManager;
  102430. }());
  102431. BABYLON.AssetsManager = AssetsManager;
  102432. })(BABYLON || (BABYLON = {}));
  102433. //# sourceMappingURL=babylon.assetsManager.js.map
  102434. var BABYLON;
  102435. (function (BABYLON) {
  102436. var serializedGeometries = [];
  102437. var serializeGeometry = function (geometry, serializationGeometries) {
  102438. if (serializedGeometries[geometry.id]) {
  102439. return;
  102440. }
  102441. if (geometry.doNotSerialize) {
  102442. return;
  102443. }
  102444. if (geometry instanceof BABYLON.BoxGeometry) {
  102445. serializationGeometries.boxes.push(geometry.serialize());
  102446. }
  102447. else if (geometry instanceof BABYLON.SphereGeometry) {
  102448. serializationGeometries.spheres.push(geometry.serialize());
  102449. }
  102450. else if (geometry instanceof BABYLON.CylinderGeometry) {
  102451. serializationGeometries.cylinders.push(geometry.serialize());
  102452. }
  102453. else if (geometry instanceof BABYLON.TorusGeometry) {
  102454. serializationGeometries.toruses.push(geometry.serialize());
  102455. }
  102456. else if (geometry instanceof BABYLON.GroundGeometry) {
  102457. serializationGeometries.grounds.push(geometry.serialize());
  102458. }
  102459. else if (geometry instanceof BABYLON.Plane) {
  102460. serializationGeometries.planes.push(geometry.serialize());
  102461. }
  102462. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  102463. serializationGeometries.torusKnots.push(geometry.serialize());
  102464. }
  102465. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  102466. throw new Error("Unknown primitive type");
  102467. }
  102468. else {
  102469. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  102470. }
  102471. serializedGeometries[geometry.id] = true;
  102472. };
  102473. var serializeMesh = function (mesh, serializationScene) {
  102474. var serializationObject = {};
  102475. // Geometry
  102476. var geometry = mesh._geometry;
  102477. if (geometry) {
  102478. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  102479. // 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
  102480. serializeGeometry(geometry, serializationScene.geometries);
  102481. }
  102482. }
  102483. // Custom
  102484. if (mesh.serialize) {
  102485. mesh.serialize(serializationObject);
  102486. }
  102487. return serializationObject;
  102488. };
  102489. var finalizeSingleMesh = function (mesh, serializationObject) {
  102490. //only works if the mesh is already loaded
  102491. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  102492. //serialize material
  102493. if (mesh.material) {
  102494. if (mesh.material instanceof BABYLON.MultiMaterial) {
  102495. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  102496. serializationObject.materials = serializationObject.materials || [];
  102497. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  102498. serializationObject.multiMaterials.push(mesh.material.serialize());
  102499. var _loop_1 = function (submaterial) {
  102500. if (submaterial) {
  102501. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  102502. serializationObject.materials.push(submaterial.serialize());
  102503. }
  102504. }
  102505. };
  102506. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  102507. var submaterial = _a[_i];
  102508. _loop_1(submaterial);
  102509. }
  102510. }
  102511. }
  102512. else {
  102513. serializationObject.materials = serializationObject.materials || [];
  102514. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  102515. serializationObject.materials.push(mesh.material.serialize());
  102516. }
  102517. }
  102518. }
  102519. //serialize geometry
  102520. var geometry = mesh._geometry;
  102521. if (geometry) {
  102522. if (!serializationObject.geometries) {
  102523. serializationObject.geometries = {};
  102524. serializationObject.geometries.boxes = [];
  102525. serializationObject.geometries.spheres = [];
  102526. serializationObject.geometries.cylinders = [];
  102527. serializationObject.geometries.toruses = [];
  102528. serializationObject.geometries.grounds = [];
  102529. serializationObject.geometries.planes = [];
  102530. serializationObject.geometries.torusKnots = [];
  102531. serializationObject.geometries.vertexData = [];
  102532. }
  102533. serializeGeometry(geometry, serializationObject.geometries);
  102534. }
  102535. // Skeletons
  102536. if (mesh.skeleton) {
  102537. serializationObject.skeletons = serializationObject.skeletons || [];
  102538. serializationObject.skeletons.push(mesh.skeleton.serialize());
  102539. }
  102540. //serialize the actual mesh
  102541. serializationObject.meshes = serializationObject.meshes || [];
  102542. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  102543. }
  102544. };
  102545. var SceneSerializer = /** @class */ (function () {
  102546. function SceneSerializer() {
  102547. }
  102548. SceneSerializer.ClearCache = function () {
  102549. serializedGeometries = [];
  102550. };
  102551. SceneSerializer.Serialize = function (scene) {
  102552. var serializationObject = {};
  102553. SceneSerializer.ClearCache();
  102554. // Scene
  102555. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  102556. serializationObject.autoClear = scene.autoClear;
  102557. serializationObject.clearColor = scene.clearColor.asArray();
  102558. serializationObject.ambientColor = scene.ambientColor.asArray();
  102559. serializationObject.gravity = scene.gravity.asArray();
  102560. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  102561. serializationObject.workerCollisions = scene.workerCollisions;
  102562. // Fog
  102563. if (scene.fogMode && scene.fogMode !== 0) {
  102564. serializationObject.fogMode = scene.fogMode;
  102565. serializationObject.fogColor = scene.fogColor.asArray();
  102566. serializationObject.fogStart = scene.fogStart;
  102567. serializationObject.fogEnd = scene.fogEnd;
  102568. serializationObject.fogDensity = scene.fogDensity;
  102569. }
  102570. //Physics
  102571. if (scene.isPhysicsEnabled()) {
  102572. var physicEngine = scene.getPhysicsEngine();
  102573. if (physicEngine) {
  102574. serializationObject.physicsEnabled = true;
  102575. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  102576. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  102577. }
  102578. }
  102579. // Metadata
  102580. if (scene.metadata) {
  102581. serializationObject.metadata = scene.metadata;
  102582. }
  102583. // Morph targets
  102584. serializationObject.morphTargetManagers = [];
  102585. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  102586. var abstractMesh = _a[_i];
  102587. var manager = abstractMesh.morphTargetManager;
  102588. if (manager) {
  102589. serializationObject.morphTargetManagers.push(manager.serialize());
  102590. }
  102591. }
  102592. // Lights
  102593. serializationObject.lights = [];
  102594. var index;
  102595. var light;
  102596. for (index = 0; index < scene.lights.length; index++) {
  102597. light = scene.lights[index];
  102598. if (!light.doNotSerialize) {
  102599. serializationObject.lights.push(light.serialize());
  102600. }
  102601. }
  102602. // Cameras
  102603. serializationObject.cameras = [];
  102604. for (index = 0; index < scene.cameras.length; index++) {
  102605. var camera = scene.cameras[index];
  102606. if (!camera.doNotSerialize) {
  102607. serializationObject.cameras.push(camera.serialize());
  102608. }
  102609. }
  102610. if (scene.activeCamera) {
  102611. serializationObject.activeCameraID = scene.activeCamera.id;
  102612. }
  102613. // Animations
  102614. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  102615. // Materials
  102616. serializationObject.materials = [];
  102617. serializationObject.multiMaterials = [];
  102618. var material;
  102619. for (index = 0; index < scene.materials.length; index++) {
  102620. material = scene.materials[index];
  102621. if (!material.doNotSerialize) {
  102622. serializationObject.materials.push(material.serialize());
  102623. }
  102624. }
  102625. // MultiMaterials
  102626. serializationObject.multiMaterials = [];
  102627. for (index = 0; index < scene.multiMaterials.length; index++) {
  102628. var multiMaterial = scene.multiMaterials[index];
  102629. serializationObject.multiMaterials.push(multiMaterial.serialize());
  102630. }
  102631. // Environment texture
  102632. if (scene.environmentTexture) {
  102633. serializationObject.environmentTexture = scene.environmentTexture.name;
  102634. }
  102635. // Skeletons
  102636. serializationObject.skeletons = [];
  102637. for (index = 0; index < scene.skeletons.length; index++) {
  102638. var skeleton = scene.skeletons[index];
  102639. if (!skeleton.doNotSerialize) {
  102640. serializationObject.skeletons.push(skeleton.serialize());
  102641. }
  102642. }
  102643. // Transform nodes
  102644. serializationObject.transformNodes = [];
  102645. for (index = 0; index < scene.transformNodes.length; index++) {
  102646. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  102647. }
  102648. // Geometries
  102649. serializationObject.geometries = {};
  102650. serializationObject.geometries.boxes = [];
  102651. serializationObject.geometries.spheres = [];
  102652. serializationObject.geometries.cylinders = [];
  102653. serializationObject.geometries.toruses = [];
  102654. serializationObject.geometries.grounds = [];
  102655. serializationObject.geometries.planes = [];
  102656. serializationObject.geometries.torusKnots = [];
  102657. serializationObject.geometries.vertexData = [];
  102658. serializedGeometries = [];
  102659. var geometries = scene.getGeometries();
  102660. for (index = 0; index < geometries.length; index++) {
  102661. var geometry = geometries[index];
  102662. if (geometry.isReady()) {
  102663. serializeGeometry(geometry, serializationObject.geometries);
  102664. }
  102665. }
  102666. // Meshes
  102667. serializationObject.meshes = [];
  102668. for (index = 0; index < scene.meshes.length; index++) {
  102669. var abstractMesh = scene.meshes[index];
  102670. if (abstractMesh instanceof BABYLON.Mesh) {
  102671. var mesh = abstractMesh;
  102672. if (!mesh.doNotSerialize) {
  102673. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  102674. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  102675. }
  102676. }
  102677. }
  102678. }
  102679. // Particles Systems
  102680. serializationObject.particleSystems = [];
  102681. for (index = 0; index < scene.particleSystems.length; index++) {
  102682. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  102683. }
  102684. // Shadows
  102685. serializationObject.shadowGenerators = [];
  102686. for (index = 0; index < scene.lights.length; index++) {
  102687. light = scene.lights[index];
  102688. var shadowGenerator = light.getShadowGenerator();
  102689. if (shadowGenerator) {
  102690. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  102691. }
  102692. }
  102693. // Action Manager
  102694. if (scene.actionManager) {
  102695. serializationObject.actions = scene.actionManager.serialize("scene");
  102696. }
  102697. // Audio
  102698. serializationObject.sounds = [];
  102699. for (index = 0; index < scene.soundTracks.length; index++) {
  102700. var soundtrack = scene.soundTracks[index];
  102701. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  102702. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  102703. }
  102704. }
  102705. // Components
  102706. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  102707. var component = _c[_b];
  102708. component.serialize(serializationObject);
  102709. }
  102710. return serializationObject;
  102711. };
  102712. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  102713. if (withParents === void 0) { withParents = false; }
  102714. if (withChildren === void 0) { withChildren = false; }
  102715. var serializationObject = {};
  102716. SceneSerializer.ClearCache();
  102717. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  102718. if (withParents || withChildren) {
  102719. //deliberate for loop! not for each, appended should be processed as well.
  102720. for (var i = 0; i < toSerialize.length; ++i) {
  102721. if (withChildren) {
  102722. toSerialize[i].getDescendants().forEach(function (node) {
  102723. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  102724. toSerialize.push(node);
  102725. }
  102726. });
  102727. }
  102728. //make sure the array doesn't contain the object already
  102729. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  102730. toSerialize.push(toSerialize[i].parent);
  102731. }
  102732. }
  102733. }
  102734. toSerialize.forEach(function (mesh) {
  102735. finalizeSingleMesh(mesh, serializationObject);
  102736. });
  102737. return serializationObject;
  102738. };
  102739. return SceneSerializer;
  102740. }());
  102741. BABYLON.SceneSerializer = SceneSerializer;
  102742. })(BABYLON || (BABYLON = {}));
  102743. //# sourceMappingURL=babylon.sceneSerializer.js.map
  102744. var BABYLON;
  102745. (function (BABYLON) {
  102746. /**
  102747. * Class used to generate realtime reflection / refraction cube textures
  102748. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  102749. */
  102750. var ReflectionProbe = /** @class */ (function () {
  102751. /**
  102752. * Creates a new reflection probe
  102753. * @param name defines the name of the probe
  102754. * @param size defines the texture resolution (for each face)
  102755. * @param scene defines the hosting scene
  102756. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  102757. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  102758. */
  102759. function ReflectionProbe(
  102760. /** defines the name of the probe */
  102761. name, size, scene, generateMipMaps, useFloat) {
  102762. if (generateMipMaps === void 0) { generateMipMaps = true; }
  102763. if (useFloat === void 0) { useFloat = false; }
  102764. var _this = this;
  102765. this.name = name;
  102766. this._viewMatrix = BABYLON.Matrix.Identity();
  102767. this._target = BABYLON.Vector3.Zero();
  102768. this._add = BABYLON.Vector3.Zero();
  102769. this._invertYAxis = false;
  102770. /** Gets or sets probe position (center of the cube map) */
  102771. this.position = BABYLON.Vector3.Zero();
  102772. this._scene = scene;
  102773. this._scene.reflectionProbes.push(this);
  102774. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  102775. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  102776. switch (faceIndex) {
  102777. case 0:
  102778. _this._add.copyFromFloats(1, 0, 0);
  102779. break;
  102780. case 1:
  102781. _this._add.copyFromFloats(-1, 0, 0);
  102782. break;
  102783. case 2:
  102784. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  102785. break;
  102786. case 3:
  102787. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  102788. break;
  102789. case 4:
  102790. _this._add.copyFromFloats(0, 0, 1);
  102791. break;
  102792. case 5:
  102793. _this._add.copyFromFloats(0, 0, -1);
  102794. break;
  102795. }
  102796. if (_this._attachedMesh) {
  102797. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  102798. }
  102799. _this.position.addToRef(_this._add, _this._target);
  102800. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  102801. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  102802. scene._forcedViewPosition = _this.position;
  102803. });
  102804. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  102805. scene._forcedViewPosition = null;
  102806. scene.updateTransformMatrix(true);
  102807. });
  102808. if (scene.activeCamera) {
  102809. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  102810. }
  102811. }
  102812. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  102813. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  102814. get: function () {
  102815. return this._renderTargetTexture.samples;
  102816. },
  102817. set: function (value) {
  102818. this._renderTargetTexture.samples = value;
  102819. },
  102820. enumerable: true,
  102821. configurable: true
  102822. });
  102823. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  102824. /** Gets or sets the refresh rate to use (on every frame by default) */
  102825. get: function () {
  102826. return this._renderTargetTexture.refreshRate;
  102827. },
  102828. set: function (value) {
  102829. this._renderTargetTexture.refreshRate = value;
  102830. },
  102831. enumerable: true,
  102832. configurable: true
  102833. });
  102834. /**
  102835. * Gets the hosting scene
  102836. * @returns a Scene
  102837. */
  102838. ReflectionProbe.prototype.getScene = function () {
  102839. return this._scene;
  102840. };
  102841. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  102842. /** Gets the internal CubeTexture used to render to */
  102843. get: function () {
  102844. return this._renderTargetTexture;
  102845. },
  102846. enumerable: true,
  102847. configurable: true
  102848. });
  102849. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  102850. /** Gets the list of meshes to render */
  102851. get: function () {
  102852. return this._renderTargetTexture.renderList;
  102853. },
  102854. enumerable: true,
  102855. configurable: true
  102856. });
  102857. /**
  102858. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  102859. * @param mesh defines the mesh to attach to
  102860. */
  102861. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  102862. this._attachedMesh = mesh;
  102863. };
  102864. /**
  102865. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  102866. * @param renderingGroupId The rendering group id corresponding to its index
  102867. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  102868. */
  102869. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  102870. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  102871. };
  102872. /**
  102873. * Clean all associated resources
  102874. */
  102875. ReflectionProbe.prototype.dispose = function () {
  102876. var index = this._scene.reflectionProbes.indexOf(this);
  102877. if (index !== -1) {
  102878. // Remove from the scene if found
  102879. this._scene.reflectionProbes.splice(index, 1);
  102880. }
  102881. if (this._renderTargetTexture) {
  102882. this._renderTargetTexture.dispose();
  102883. this._renderTargetTexture = null;
  102884. }
  102885. };
  102886. return ReflectionProbe;
  102887. }());
  102888. BABYLON.ReflectionProbe = ReflectionProbe;
  102889. })(BABYLON || (BABYLON = {}));
  102890. //# sourceMappingURL=babylon.reflectionProbe.js.map
  102891. var BABYLON;
  102892. (function (BABYLON) {
  102893. /**
  102894. * Defines the layer scene component responsible to manage any layers
  102895. * in a given scene.
  102896. */
  102897. var LayerSceneComponent = /** @class */ (function () {
  102898. /**
  102899. * Creates a new instance of the component for the given scene
  102900. * @param scene Defines the scene to register the component in
  102901. */
  102902. function LayerSceneComponent(scene) {
  102903. /**
  102904. * The component name helpfull to identify the component in the list of scene components.
  102905. */
  102906. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  102907. this.scene = scene;
  102908. this._engine = scene.getEngine();
  102909. scene.layers = new Array();
  102910. }
  102911. /**
  102912. * Registers the component in a given scene
  102913. */
  102914. LayerSceneComponent.prototype.register = function () {
  102915. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  102916. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  102917. };
  102918. /**
  102919. * Rebuilds the elements related to this component in case of
  102920. * context lost for instance.
  102921. */
  102922. LayerSceneComponent.prototype.rebuild = function () {
  102923. var layers = this.scene.layers;
  102924. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  102925. var layer = layers_1[_i];
  102926. layer._rebuild();
  102927. }
  102928. };
  102929. /**
  102930. * Disposes the component and the associated ressources.
  102931. */
  102932. LayerSceneComponent.prototype.dispose = function () {
  102933. var layers = this.scene.layers;
  102934. while (layers.length) {
  102935. layers[0].dispose();
  102936. }
  102937. };
  102938. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  102939. var layers = this.scene.layers;
  102940. if (layers.length) {
  102941. this._engine.setDepthBuffer(false);
  102942. var cameraLayerMask = camera.layerMask;
  102943. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  102944. var layer = layers_2[_i];
  102945. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  102946. layer.render();
  102947. }
  102948. }
  102949. this._engine.setDepthBuffer(true);
  102950. }
  102951. };
  102952. LayerSceneComponent.prototype._drawBackground = function (camera) {
  102953. this._draw(camera, true);
  102954. };
  102955. LayerSceneComponent.prototype._drawForeground = function (camera) {
  102956. this._draw(camera, false);
  102957. };
  102958. return LayerSceneComponent;
  102959. }());
  102960. BABYLON.LayerSceneComponent = LayerSceneComponent;
  102961. })(BABYLON || (BABYLON = {}));
  102962. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  102963. var BABYLON;
  102964. (function (BABYLON) {
  102965. var Layer = /** @class */ (function () {
  102966. function Layer(name, imgUrl, scene, isBackground, color) {
  102967. this.name = name;
  102968. this.scale = new BABYLON.Vector2(1, 1);
  102969. this.offset = new BABYLON.Vector2(0, 0);
  102970. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  102971. this.layerMask = 0x0FFFFFFF;
  102972. this._vertexBuffers = {};
  102973. // Events
  102974. /**
  102975. * An event triggered when the layer is disposed.
  102976. */
  102977. this.onDisposeObservable = new BABYLON.Observable();
  102978. /**
  102979. * An event triggered before rendering the scene
  102980. */
  102981. this.onBeforeRenderObservable = new BABYLON.Observable();
  102982. /**
  102983. * An event triggered after rendering the scene
  102984. */
  102985. this.onAfterRenderObservable = new BABYLON.Observable();
  102986. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  102987. this.isBackground = isBackground === undefined ? true : isBackground;
  102988. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  102989. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  102990. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  102991. if (!layerComponent) {
  102992. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  102993. this._scene._addComponent(layerComponent);
  102994. }
  102995. this._scene.layers.push(this);
  102996. var engine = this._scene.getEngine();
  102997. // VBO
  102998. var vertices = [];
  102999. vertices.push(1, 1);
  103000. vertices.push(-1, 1);
  103001. vertices.push(-1, -1);
  103002. vertices.push(1, -1);
  103003. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  103004. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  103005. this._createIndexBuffer();
  103006. // Effects
  103007. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  103008. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  103009. }
  103010. Object.defineProperty(Layer.prototype, "onDispose", {
  103011. set: function (callback) {
  103012. if (this._onDisposeObserver) {
  103013. this.onDisposeObservable.remove(this._onDisposeObserver);
  103014. }
  103015. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  103016. },
  103017. enumerable: true,
  103018. configurable: true
  103019. });
  103020. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  103021. set: function (callback) {
  103022. if (this._onBeforeRenderObserver) {
  103023. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  103024. }
  103025. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  103026. },
  103027. enumerable: true,
  103028. configurable: true
  103029. });
  103030. Object.defineProperty(Layer.prototype, "onAfterRender", {
  103031. set: function (callback) {
  103032. if (this._onAfterRenderObserver) {
  103033. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  103034. }
  103035. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  103036. },
  103037. enumerable: true,
  103038. configurable: true
  103039. });
  103040. Layer.prototype._createIndexBuffer = function () {
  103041. var engine = this._scene.getEngine();
  103042. // Indices
  103043. var indices = [];
  103044. indices.push(0);
  103045. indices.push(1);
  103046. indices.push(2);
  103047. indices.push(0);
  103048. indices.push(2);
  103049. indices.push(3);
  103050. this._indexBuffer = engine.createIndexBuffer(indices);
  103051. };
  103052. /** @hidden */
  103053. Layer.prototype._rebuild = function () {
  103054. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  103055. if (vb) {
  103056. vb._rebuild();
  103057. }
  103058. this._createIndexBuffer();
  103059. };
  103060. Layer.prototype.render = function () {
  103061. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  103062. // Check
  103063. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  103064. return;
  103065. var engine = this._scene.getEngine();
  103066. this.onBeforeRenderObservable.notifyObservers(this);
  103067. // Render
  103068. engine.enableEffect(currentEffect);
  103069. engine.setState(false);
  103070. // Texture
  103071. currentEffect.setTexture("textureSampler", this.texture);
  103072. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  103073. // Color
  103074. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  103075. // Scale / offset
  103076. currentEffect.setVector2("offset", this.offset);
  103077. currentEffect.setVector2("scale", this.scale);
  103078. // VBOs
  103079. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  103080. // Draw order
  103081. if (!this.alphaTest) {
  103082. engine.setAlphaMode(this.alphaBlendingMode);
  103083. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  103084. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  103085. }
  103086. else {
  103087. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  103088. }
  103089. this.onAfterRenderObservable.notifyObservers(this);
  103090. };
  103091. Layer.prototype.dispose = function () {
  103092. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  103093. if (vertexBuffer) {
  103094. vertexBuffer.dispose();
  103095. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  103096. }
  103097. if (this._indexBuffer) {
  103098. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  103099. this._indexBuffer = null;
  103100. }
  103101. if (this.texture) {
  103102. this.texture.dispose();
  103103. this.texture = null;
  103104. }
  103105. // Remove from scene
  103106. var index = this._scene.layers.indexOf(this);
  103107. this._scene.layers.splice(index, 1);
  103108. // Callback
  103109. this.onDisposeObservable.notifyObservers(this);
  103110. this.onDisposeObservable.clear();
  103111. this.onAfterRenderObservable.clear();
  103112. this.onBeforeRenderObservable.clear();
  103113. };
  103114. return Layer;
  103115. }());
  103116. BABYLON.Layer = Layer;
  103117. })(BABYLON || (BABYLON = {}));
  103118. //# sourceMappingURL=babylon.layer.js.map
  103119. var BABYLON;
  103120. (function (BABYLON) {
  103121. var TextureTools = /** @class */ (function () {
  103122. function TextureTools() {
  103123. }
  103124. /**
  103125. * Uses the GPU to create a copy texture rescaled at a given size
  103126. * @param texture Texture to copy from
  103127. * @param width Desired width
  103128. * @param height Desired height
  103129. * @return Generated texture
  103130. */
  103131. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  103132. if (useBilinearMode === void 0) { useBilinearMode = true; }
  103133. var scene = texture.getScene();
  103134. var engine = scene.getEngine();
  103135. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  103136. rtt.wrapU = texture.wrapU;
  103137. rtt.wrapV = texture.wrapV;
  103138. rtt.uOffset = texture.uOffset;
  103139. rtt.vOffset = texture.vOffset;
  103140. rtt.uScale = texture.uScale;
  103141. rtt.vScale = texture.vScale;
  103142. rtt.uAng = texture.uAng;
  103143. rtt.vAng = texture.vAng;
  103144. rtt.wAng = texture.wAng;
  103145. rtt.coordinatesIndex = texture.coordinatesIndex;
  103146. rtt.level = texture.level;
  103147. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  103148. rtt._texture.isReady = false;
  103149. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103150. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103151. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  103152. passPostProcess.getEffect().executeWhenCompiled(function () {
  103153. passPostProcess.onApply = function (effect) {
  103154. effect.setTexture("textureSampler", texture);
  103155. };
  103156. var internalTexture = rtt.getInternalTexture();
  103157. if (internalTexture) {
  103158. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  103159. engine.unBindFramebuffer(internalTexture);
  103160. rtt.disposeFramebufferObjects();
  103161. passPostProcess.dispose();
  103162. internalTexture.isReady = true;
  103163. }
  103164. });
  103165. return rtt;
  103166. };
  103167. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  103168. if (!scene._environmentBRDFTexture) {
  103169. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  103170. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103171. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103172. scene._environmentBRDFTexture = texture;
  103173. }
  103174. return scene._environmentBRDFTexture;
  103175. };
  103176. 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=";
  103177. return TextureTools;
  103178. }());
  103179. BABYLON.TextureTools = TextureTools;
  103180. })(BABYLON || (BABYLON = {}));
  103181. //# sourceMappingURL=babylon.textureTools.js.map
  103182. var BABYLON;
  103183. (function (BABYLON) {
  103184. var FramingBehavior = /** @class */ (function () {
  103185. function FramingBehavior() {
  103186. this._mode = FramingBehavior.FitFrustumSidesMode;
  103187. this._radiusScale = 1.0;
  103188. this._positionScale = 0.5;
  103189. this._defaultElevation = 0.3;
  103190. this._elevationReturnTime = 1500;
  103191. this._elevationReturnWaitTime = 1000;
  103192. this._zoomStopsAnimation = false;
  103193. this._framingTime = 1500;
  103194. this._isPointerDown = false;
  103195. this._lastInteractionTime = -Infinity;
  103196. // Framing control
  103197. this._animatables = new Array();
  103198. this._betaIsAnimating = false;
  103199. }
  103200. Object.defineProperty(FramingBehavior.prototype, "name", {
  103201. get: function () {
  103202. return "Framing";
  103203. },
  103204. enumerable: true,
  103205. configurable: true
  103206. });
  103207. Object.defineProperty(FramingBehavior.prototype, "mode", {
  103208. /**
  103209. * Gets current mode used by the behavior.
  103210. */
  103211. get: function () {
  103212. return this._mode;
  103213. },
  103214. /**
  103215. * Sets the current mode used by the behavior
  103216. */
  103217. set: function (mode) {
  103218. this._mode = mode;
  103219. },
  103220. enumerable: true,
  103221. configurable: true
  103222. });
  103223. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  103224. /**
  103225. * Gets the scale applied to the radius
  103226. */
  103227. get: function () {
  103228. return this._radiusScale;
  103229. },
  103230. /**
  103231. * Sets the scale applied to the radius (1 by default)
  103232. */
  103233. set: function (radius) {
  103234. this._radiusScale = radius;
  103235. },
  103236. enumerable: true,
  103237. configurable: true
  103238. });
  103239. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  103240. /**
  103241. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  103242. */
  103243. get: function () {
  103244. return this._positionScale;
  103245. },
  103246. /**
  103247. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  103248. */
  103249. set: function (scale) {
  103250. this._positionScale = scale;
  103251. },
  103252. enumerable: true,
  103253. configurable: true
  103254. });
  103255. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  103256. /**
  103257. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  103258. * behaviour is triggered, in radians.
  103259. */
  103260. get: function () {
  103261. return this._defaultElevation;
  103262. },
  103263. /**
  103264. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  103265. * behaviour is triggered, in radians.
  103266. */
  103267. set: function (elevation) {
  103268. this._defaultElevation = elevation;
  103269. },
  103270. enumerable: true,
  103271. configurable: true
  103272. });
  103273. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  103274. /**
  103275. * Gets the time (in milliseconds) taken to return to the default beta position.
  103276. * Negative value indicates camera should not return to default.
  103277. */
  103278. get: function () {
  103279. return this._elevationReturnTime;
  103280. },
  103281. /**
  103282. * Sets the time (in milliseconds) taken to return to the default beta position.
  103283. * Negative value indicates camera should not return to default.
  103284. */
  103285. set: function (speed) {
  103286. this._elevationReturnTime = speed;
  103287. },
  103288. enumerable: true,
  103289. configurable: true
  103290. });
  103291. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  103292. /**
  103293. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  103294. */
  103295. get: function () {
  103296. return this._elevationReturnWaitTime;
  103297. },
  103298. /**
  103299. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  103300. */
  103301. set: function (time) {
  103302. this._elevationReturnWaitTime = time;
  103303. },
  103304. enumerable: true,
  103305. configurable: true
  103306. });
  103307. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  103308. /**
  103309. * Gets the flag that indicates if user zooming should stop animation.
  103310. */
  103311. get: function () {
  103312. return this._zoomStopsAnimation;
  103313. },
  103314. /**
  103315. * Sets the flag that indicates if user zooming should stop animation.
  103316. */
  103317. set: function (flag) {
  103318. this._zoomStopsAnimation = flag;
  103319. },
  103320. enumerable: true,
  103321. configurable: true
  103322. });
  103323. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  103324. /**
  103325. * Gets the transition time when framing the mesh, in milliseconds
  103326. */
  103327. get: function () {
  103328. return this._framingTime;
  103329. },
  103330. /**
  103331. * Sets the transition time when framing the mesh, in milliseconds
  103332. */
  103333. set: function (time) {
  103334. this._framingTime = time;
  103335. },
  103336. enumerable: true,
  103337. configurable: true
  103338. });
  103339. FramingBehavior.prototype.init = function () {
  103340. // Do notihng
  103341. };
  103342. FramingBehavior.prototype.attach = function (camera) {
  103343. var _this = this;
  103344. this._attachedCamera = camera;
  103345. var scene = this._attachedCamera.getScene();
  103346. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  103347. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  103348. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  103349. _this._isPointerDown = true;
  103350. return;
  103351. }
  103352. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  103353. _this._isPointerDown = false;
  103354. }
  103355. });
  103356. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  103357. if (mesh) {
  103358. _this.zoomOnMesh(mesh);
  103359. }
  103360. });
  103361. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  103362. // Stop the animation if there is user interaction and the animation should stop for this interaction
  103363. _this._applyUserInteraction();
  103364. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  103365. // back to the default position after a given timeout
  103366. _this._maintainCameraAboveGround();
  103367. });
  103368. };
  103369. FramingBehavior.prototype.detach = function () {
  103370. if (!this._attachedCamera) {
  103371. return;
  103372. }
  103373. var scene = this._attachedCamera.getScene();
  103374. if (this._onPrePointerObservableObserver) {
  103375. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  103376. }
  103377. if (this._onAfterCheckInputsObserver) {
  103378. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  103379. }
  103380. if (this._onMeshTargetChangedObserver) {
  103381. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  103382. }
  103383. this._attachedCamera = null;
  103384. };
  103385. /**
  103386. * Targets the given mesh and updates zoom level accordingly.
  103387. * @param mesh The mesh to target.
  103388. * @param radius Optional. If a cached radius position already exists, overrides default.
  103389. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  103390. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  103391. * @param onAnimationEnd Callback triggered at the end of the framing animation
  103392. */
  103393. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  103394. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  103395. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  103396. mesh.computeWorldMatrix(true);
  103397. var boundingBox = mesh.getBoundingInfo().boundingBox;
  103398. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  103399. };
  103400. /**
  103401. * Targets the given mesh with its children and updates zoom level accordingly.
  103402. * @param mesh The mesh to target.
  103403. * @param radius Optional. If a cached radius position already exists, overrides default.
  103404. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  103405. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  103406. * @param onAnimationEnd Callback triggered at the end of the framing animation
  103407. */
  103408. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  103409. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  103410. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  103411. mesh.computeWorldMatrix(true);
  103412. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  103413. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  103414. };
  103415. /**
  103416. * Targets the given meshes with their children and updates zoom level accordingly.
  103417. * @param meshes The mesh to target.
  103418. * @param radius Optional. If a cached radius position already exists, overrides default.
  103419. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  103420. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  103421. * @param onAnimationEnd Callback triggered at the end of the framing animation
  103422. */
  103423. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  103424. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  103425. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  103426. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  103427. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  103428. for (var i = 0; i < meshes.length; i++) {
  103429. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  103430. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  103431. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  103432. }
  103433. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  103434. };
  103435. /**
  103436. * Targets the given mesh and updates zoom level accordingly.
  103437. * @param mesh The mesh to target.
  103438. * @param radius Optional. If a cached radius position already exists, overrides default.
  103439. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  103440. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  103441. * @param onAnimationEnd Callback triggered at the end of the framing animation
  103442. */
  103443. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  103444. var _this = this;
  103445. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  103446. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  103447. var zoomTarget;
  103448. if (!this._attachedCamera) {
  103449. return;
  103450. }
  103451. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  103452. var bottom = minimumWorld.y;
  103453. var top = maximumWorld.y;
  103454. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  103455. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  103456. if (focusOnOriginXZ) {
  103457. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  103458. }
  103459. else {
  103460. var centerWorld = minimumWorld.add(radiusWorld);
  103461. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  103462. }
  103463. if (!this._vectorTransition) {
  103464. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  103465. }
  103466. this._betaIsAnimating = true;
  103467. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  103468. if (animatable) {
  103469. this._animatables.push(animatable);
  103470. }
  103471. // sets the radius and lower radius bounds
  103472. // Small delta ensures camera is not always at lower zoom limit.
  103473. var radius = 0;
  103474. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  103475. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  103476. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  103477. radius = position;
  103478. }
  103479. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  103480. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  103481. if (this._attachedCamera.lowerRadiusLimit === null) {
  103482. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  103483. }
  103484. }
  103485. // Set sensibilities
  103486. var extend = maximumWorld.subtract(minimumWorld).length();
  103487. this._attachedCamera.panningSensibility = 5000 / extend;
  103488. this._attachedCamera.wheelPrecision = 100 / radius;
  103489. // transition to new radius
  103490. if (!this._radiusTransition) {
  103491. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  103492. }
  103493. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  103494. _this.stopAllAnimations();
  103495. if (onAnimationEnd) {
  103496. onAnimationEnd();
  103497. }
  103498. if (_this._attachedCamera) {
  103499. _this._attachedCamera.storeState();
  103500. }
  103501. });
  103502. if (animatable) {
  103503. this._animatables.push(animatable);
  103504. }
  103505. };
  103506. /**
  103507. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  103508. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  103509. * frustum width.
  103510. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  103511. * to fully enclose the mesh in the viewing frustum.
  103512. */
  103513. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  103514. var size = maximumWorld.subtract(minimumWorld);
  103515. var boxVectorGlobalDiagonal = size.length();
  103516. var frustumSlope = this._getFrustumSlope();
  103517. // Formula for setting distance
  103518. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  103519. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  103520. // Horizon distance
  103521. var radius = radiusWithoutFraming * this._radiusScale;
  103522. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  103523. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  103524. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  103525. var camera = this._attachedCamera;
  103526. if (!camera) {
  103527. return 0;
  103528. }
  103529. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  103530. // Don't exceed the requested limit
  103531. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  103532. }
  103533. // Don't exceed the upper radius limit
  103534. if (camera.upperRadiusLimit) {
  103535. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  103536. }
  103537. return distance;
  103538. };
  103539. /**
  103540. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  103541. * is automatically returned to its default position (expected to be above ground plane).
  103542. */
  103543. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  103544. var _this = this;
  103545. if (this._elevationReturnTime < 0) {
  103546. return;
  103547. }
  103548. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  103549. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  103550. var limitBeta = Math.PI * 0.5;
  103551. // Bring the camera back up if below the ground plane
  103552. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  103553. this._betaIsAnimating = true;
  103554. //Transition to new position
  103555. this.stopAllAnimations();
  103556. if (!this._betaTransition) {
  103557. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  103558. }
  103559. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  103560. _this._clearAnimationLocks();
  103561. _this.stopAllAnimations();
  103562. });
  103563. if (animatabe) {
  103564. this._animatables.push(animatabe);
  103565. }
  103566. }
  103567. };
  103568. /**
  103569. * Returns the frustum slope based on the canvas ratio and camera FOV
  103570. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  103571. */
  103572. FramingBehavior.prototype._getFrustumSlope = function () {
  103573. // Calculate the viewport ratio
  103574. // Aspect Ratio is Height/Width.
  103575. var camera = this._attachedCamera;
  103576. if (!camera) {
  103577. return BABYLON.Vector2.Zero();
  103578. }
  103579. var engine = camera.getScene().getEngine();
  103580. var aspectRatio = engine.getAspectRatio(camera);
  103581. // Camera FOV is the vertical field of view (top-bottom) in radians.
  103582. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  103583. var frustumSlopeY = Math.tan(camera.fov / 2);
  103584. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  103585. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  103586. // along the forward vector.
  103587. var frustumSlopeX = frustumSlopeY * aspectRatio;
  103588. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  103589. };
  103590. /**
  103591. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  103592. */
  103593. FramingBehavior.prototype._clearAnimationLocks = function () {
  103594. this._betaIsAnimating = false;
  103595. };
  103596. /**
  103597. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  103598. */
  103599. FramingBehavior.prototype._applyUserInteraction = function () {
  103600. if (this.isUserIsMoving) {
  103601. this._lastInteractionTime = BABYLON.Tools.Now;
  103602. this.stopAllAnimations();
  103603. this._clearAnimationLocks();
  103604. }
  103605. };
  103606. /**
  103607. * Stops and removes all animations that have been applied to the camera
  103608. */
  103609. FramingBehavior.prototype.stopAllAnimations = function () {
  103610. if (this._attachedCamera) {
  103611. this._attachedCamera.animations = [];
  103612. }
  103613. while (this._animatables.length) {
  103614. if (this._animatables[0]) {
  103615. this._animatables[0].onAnimationEnd = null;
  103616. this._animatables[0].stop();
  103617. }
  103618. this._animatables.shift();
  103619. }
  103620. };
  103621. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  103622. /**
  103623. * Gets a value indicating if the user is moving the camera
  103624. */
  103625. get: function () {
  103626. if (!this._attachedCamera) {
  103627. return false;
  103628. }
  103629. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  103630. this._attachedCamera.inertialBetaOffset !== 0 ||
  103631. this._attachedCamera.inertialRadiusOffset !== 0 ||
  103632. this._attachedCamera.inertialPanningX !== 0 ||
  103633. this._attachedCamera.inertialPanningY !== 0 ||
  103634. this._isPointerDown;
  103635. },
  103636. enumerable: true,
  103637. configurable: true
  103638. });
  103639. /**
  103640. * The easing function used by animations
  103641. */
  103642. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  103643. /**
  103644. * The easing mode used by animations
  103645. */
  103646. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  103647. // Statics
  103648. /**
  103649. * The camera can move all the way towards the mesh.
  103650. */
  103651. FramingBehavior.IgnoreBoundsSizeMode = 0;
  103652. /**
  103653. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  103654. */
  103655. FramingBehavior.FitFrustumSidesMode = 1;
  103656. return FramingBehavior;
  103657. }());
  103658. BABYLON.FramingBehavior = FramingBehavior;
  103659. })(BABYLON || (BABYLON = {}));
  103660. //# sourceMappingURL=babylon.framingBehavior.js.map
  103661. var BABYLON;
  103662. (function (BABYLON) {
  103663. /**
  103664. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  103665. */
  103666. var BouncingBehavior = /** @class */ (function () {
  103667. function BouncingBehavior() {
  103668. /**
  103669. * The duration of the animation, in milliseconds
  103670. */
  103671. this.transitionDuration = 450;
  103672. /**
  103673. * Length of the distance animated by the transition when lower radius is reached
  103674. */
  103675. this.lowerRadiusTransitionRange = 2;
  103676. /**
  103677. * Length of the distance animated by the transition when upper radius is reached
  103678. */
  103679. this.upperRadiusTransitionRange = -2;
  103680. this._autoTransitionRange = false;
  103681. // Animations
  103682. this._radiusIsAnimating = false;
  103683. this._radiusBounceTransition = null;
  103684. this._animatables = new Array();
  103685. }
  103686. Object.defineProperty(BouncingBehavior.prototype, "name", {
  103687. get: function () {
  103688. return "Bouncing";
  103689. },
  103690. enumerable: true,
  103691. configurable: true
  103692. });
  103693. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  103694. /**
  103695. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  103696. */
  103697. get: function () {
  103698. return this._autoTransitionRange;
  103699. },
  103700. /**
  103701. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  103702. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  103703. */
  103704. set: function (value) {
  103705. var _this = this;
  103706. if (this._autoTransitionRange === value) {
  103707. return;
  103708. }
  103709. this._autoTransitionRange = value;
  103710. var camera = this._attachedCamera;
  103711. if (!camera) {
  103712. return;
  103713. }
  103714. if (value) {
  103715. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  103716. if (!mesh) {
  103717. return;
  103718. }
  103719. mesh.computeWorldMatrix(true);
  103720. var diagonal = mesh.getBoundingInfo().diagonalLength;
  103721. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  103722. _this.upperRadiusTransitionRange = diagonal * 0.05;
  103723. });
  103724. }
  103725. else if (this._onMeshTargetChangedObserver) {
  103726. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  103727. }
  103728. },
  103729. enumerable: true,
  103730. configurable: true
  103731. });
  103732. BouncingBehavior.prototype.init = function () {
  103733. // Do notihng
  103734. };
  103735. BouncingBehavior.prototype.attach = function (camera) {
  103736. var _this = this;
  103737. this._attachedCamera = camera;
  103738. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  103739. if (!_this._attachedCamera) {
  103740. return;
  103741. }
  103742. // Add the bounce animation to the lower radius limit
  103743. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  103744. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  103745. }
  103746. // Add the bounce animation to the upper radius limit
  103747. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  103748. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  103749. }
  103750. });
  103751. };
  103752. BouncingBehavior.prototype.detach = function () {
  103753. if (!this._attachedCamera) {
  103754. return;
  103755. }
  103756. if (this._onAfterCheckInputsObserver) {
  103757. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  103758. }
  103759. if (this._onMeshTargetChangedObserver) {
  103760. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  103761. }
  103762. this._attachedCamera = null;
  103763. };
  103764. /**
  103765. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  103766. * @param radiusLimit The limit to check against.
  103767. * @return Bool to indicate if at limit.
  103768. */
  103769. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  103770. if (!this._attachedCamera) {
  103771. return false;
  103772. }
  103773. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  103774. return true;
  103775. }
  103776. return false;
  103777. };
  103778. /**
  103779. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  103780. * @param radiusDelta The delta by which to animate to. Can be negative.
  103781. */
  103782. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  103783. var _this = this;
  103784. if (!this._attachedCamera) {
  103785. return;
  103786. }
  103787. if (!this._radiusBounceTransition) {
  103788. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  103789. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  103790. }
  103791. // Prevent zoom until bounce has completed
  103792. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  103793. this._attachedCamera.wheelPrecision = Infinity;
  103794. this._attachedCamera.inertialRadiusOffset = 0;
  103795. // Animate to the radius limit
  103796. this.stopAllAnimations();
  103797. this._radiusIsAnimating = true;
  103798. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  103799. if (animatable) {
  103800. this._animatables.push(animatable);
  103801. }
  103802. };
  103803. /**
  103804. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  103805. */
  103806. BouncingBehavior.prototype._clearAnimationLocks = function () {
  103807. this._radiusIsAnimating = false;
  103808. if (this._attachedCamera) {
  103809. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  103810. }
  103811. };
  103812. /**
  103813. * Stops and removes all animations that have been applied to the camera
  103814. */
  103815. BouncingBehavior.prototype.stopAllAnimations = function () {
  103816. if (this._attachedCamera) {
  103817. this._attachedCamera.animations = [];
  103818. }
  103819. while (this._animatables.length) {
  103820. this._animatables[0].onAnimationEnd = null;
  103821. this._animatables[0].stop();
  103822. this._animatables.shift();
  103823. }
  103824. };
  103825. /**
  103826. * The easing function used by animations
  103827. */
  103828. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  103829. /**
  103830. * The easing mode used by animations
  103831. */
  103832. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  103833. return BouncingBehavior;
  103834. }());
  103835. BABYLON.BouncingBehavior = BouncingBehavior;
  103836. })(BABYLON || (BABYLON = {}));
  103837. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  103838. var BABYLON;
  103839. (function (BABYLON) {
  103840. var AutoRotationBehavior = /** @class */ (function () {
  103841. function AutoRotationBehavior() {
  103842. this._zoomStopsAnimation = false;
  103843. this._idleRotationSpeed = 0.05;
  103844. this._idleRotationWaitTime = 2000;
  103845. this._idleRotationSpinupTime = 2000;
  103846. this._isPointerDown = false;
  103847. this._lastFrameTime = null;
  103848. this._lastInteractionTime = -Infinity;
  103849. this._cameraRotationSpeed = 0;
  103850. this._lastFrameRadius = 0;
  103851. }
  103852. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  103853. get: function () {
  103854. return "AutoRotation";
  103855. },
  103856. enumerable: true,
  103857. configurable: true
  103858. });
  103859. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  103860. /**
  103861. * Gets the flag that indicates if user zooming should stop animation.
  103862. */
  103863. get: function () {
  103864. return this._zoomStopsAnimation;
  103865. },
  103866. /**
  103867. * Sets the flag that indicates if user zooming should stop animation.
  103868. */
  103869. set: function (flag) {
  103870. this._zoomStopsAnimation = flag;
  103871. },
  103872. enumerable: true,
  103873. configurable: true
  103874. });
  103875. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  103876. /**
  103877. * Gets the default speed at which the camera rotates around the model.
  103878. */
  103879. get: function () {
  103880. return this._idleRotationSpeed;
  103881. },
  103882. /**
  103883. * Sets the default speed at which the camera rotates around the model.
  103884. */
  103885. set: function (speed) {
  103886. this._idleRotationSpeed = speed;
  103887. },
  103888. enumerable: true,
  103889. configurable: true
  103890. });
  103891. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  103892. /**
  103893. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  103894. */
  103895. get: function () {
  103896. return this._idleRotationWaitTime;
  103897. },
  103898. /**
  103899. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  103900. */
  103901. set: function (time) {
  103902. this._idleRotationWaitTime = time;
  103903. },
  103904. enumerable: true,
  103905. configurable: true
  103906. });
  103907. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  103908. /**
  103909. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  103910. */
  103911. get: function () {
  103912. return this._idleRotationSpinupTime;
  103913. },
  103914. /**
  103915. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  103916. */
  103917. set: function (time) {
  103918. this._idleRotationSpinupTime = time;
  103919. },
  103920. enumerable: true,
  103921. configurable: true
  103922. });
  103923. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  103924. /**
  103925. * Gets a value indicating if the camera is currently rotating because of this behavior
  103926. */
  103927. get: function () {
  103928. return Math.abs(this._cameraRotationSpeed) > 0;
  103929. },
  103930. enumerable: true,
  103931. configurable: true
  103932. });
  103933. AutoRotationBehavior.prototype.init = function () {
  103934. // Do notihng
  103935. };
  103936. AutoRotationBehavior.prototype.attach = function (camera) {
  103937. var _this = this;
  103938. this._attachedCamera = camera;
  103939. var scene = this._attachedCamera.getScene();
  103940. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  103941. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  103942. _this._isPointerDown = true;
  103943. return;
  103944. }
  103945. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  103946. _this._isPointerDown = false;
  103947. }
  103948. });
  103949. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  103950. var now = BABYLON.Tools.Now;
  103951. var dt = 0;
  103952. if (_this._lastFrameTime != null) {
  103953. dt = now - _this._lastFrameTime;
  103954. }
  103955. _this._lastFrameTime = now;
  103956. // Stop the animation if there is user interaction and the animation should stop for this interaction
  103957. _this._applyUserInteraction();
  103958. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  103959. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  103960. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  103961. // Step camera rotation by rotation speed
  103962. if (_this._attachedCamera) {
  103963. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  103964. }
  103965. });
  103966. };
  103967. AutoRotationBehavior.prototype.detach = function () {
  103968. if (!this._attachedCamera) {
  103969. return;
  103970. }
  103971. var scene = this._attachedCamera.getScene();
  103972. if (this._onPrePointerObservableObserver) {
  103973. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  103974. }
  103975. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  103976. this._attachedCamera = null;
  103977. };
  103978. /**
  103979. * Returns true if user is scrolling.
  103980. * @return true if user is scrolling.
  103981. */
  103982. AutoRotationBehavior.prototype._userIsZooming = function () {
  103983. if (!this._attachedCamera) {
  103984. return false;
  103985. }
  103986. return this._attachedCamera.inertialRadiusOffset !== 0;
  103987. };
  103988. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  103989. if (!this._attachedCamera) {
  103990. return false;
  103991. }
  103992. var zoomHasHitLimit = false;
  103993. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  103994. zoomHasHitLimit = true;
  103995. }
  103996. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  103997. this._lastFrameRadius = this._attachedCamera.radius;
  103998. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  103999. };
  104000. /**
  104001. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  104002. */
  104003. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  104004. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  104005. this._lastInteractionTime = BABYLON.Tools.Now;
  104006. }
  104007. };
  104008. // Tools
  104009. AutoRotationBehavior.prototype._userIsMoving = function () {
  104010. if (!this._attachedCamera) {
  104011. return false;
  104012. }
  104013. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  104014. this._attachedCamera.inertialBetaOffset !== 0 ||
  104015. this._attachedCamera.inertialRadiusOffset !== 0 ||
  104016. this._attachedCamera.inertialPanningX !== 0 ||
  104017. this._attachedCamera.inertialPanningY !== 0 ||
  104018. this._isPointerDown;
  104019. };
  104020. return AutoRotationBehavior;
  104021. }());
  104022. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  104023. })(BABYLON || (BABYLON = {}));
  104024. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  104025. var BABYLON;
  104026. (function (BABYLON) {
  104027. var NullEngineOptions = /** @class */ (function () {
  104028. function NullEngineOptions() {
  104029. this.renderWidth = 512;
  104030. this.renderHeight = 256;
  104031. this.textureSize = 512;
  104032. this.deterministicLockstep = false;
  104033. this.lockstepMaxSteps = 4;
  104034. }
  104035. return NullEngineOptions;
  104036. }());
  104037. BABYLON.NullEngineOptions = NullEngineOptions;
  104038. /**
  104039. * The null engine class provides support for headless version of babylon.js.
  104040. * This can be used in server side scenario or for testing purposes
  104041. */
  104042. var NullEngine = /** @class */ (function (_super) {
  104043. __extends(NullEngine, _super);
  104044. function NullEngine(options) {
  104045. if (options === void 0) { options = new NullEngineOptions(); }
  104046. var _this = _super.call(this, null) || this;
  104047. if (options.deterministicLockstep === undefined) {
  104048. options.deterministicLockstep = false;
  104049. }
  104050. if (options.lockstepMaxSteps === undefined) {
  104051. options.lockstepMaxSteps = 4;
  104052. }
  104053. _this._options = options;
  104054. // Init caps
  104055. // We consider we are on a webgl1 capable device
  104056. _this._caps = new BABYLON.EngineCapabilities();
  104057. _this._caps.maxTexturesImageUnits = 16;
  104058. _this._caps.maxVertexTextureImageUnits = 16;
  104059. _this._caps.maxTextureSize = 512;
  104060. _this._caps.maxCubemapTextureSize = 512;
  104061. _this._caps.maxRenderTextureSize = 512;
  104062. _this._caps.maxVertexAttribs = 16;
  104063. _this._caps.maxVaryingVectors = 16;
  104064. _this._caps.maxFragmentUniformVectors = 16;
  104065. _this._caps.maxVertexUniformVectors = 16;
  104066. // Extensions
  104067. _this._caps.standardDerivatives = false;
  104068. _this._caps.astc = null;
  104069. _this._caps.s3tc = null;
  104070. _this._caps.pvrtc = null;
  104071. _this._caps.etc1 = null;
  104072. _this._caps.etc2 = null;
  104073. _this._caps.textureAnisotropicFilterExtension = null;
  104074. _this._caps.maxAnisotropy = 0;
  104075. _this._caps.uintIndices = false;
  104076. _this._caps.fragmentDepthSupported = false;
  104077. _this._caps.highPrecisionShaderSupported = true;
  104078. _this._caps.colorBufferFloat = false;
  104079. _this._caps.textureFloat = false;
  104080. _this._caps.textureFloatLinearFiltering = false;
  104081. _this._caps.textureFloatRender = false;
  104082. _this._caps.textureHalfFloat = false;
  104083. _this._caps.textureHalfFloatLinearFiltering = false;
  104084. _this._caps.textureHalfFloatRender = false;
  104085. _this._caps.textureLOD = false;
  104086. _this._caps.drawBuffersExtension = false;
  104087. _this._caps.depthTextureExtension = false;
  104088. _this._caps.vertexArrayObject = false;
  104089. _this._caps.instancedArrays = false;
  104090. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  104091. // Wrappers
  104092. if (typeof URL === "undefined") {
  104093. URL = {
  104094. createObjectURL: function () { },
  104095. revokeObjectURL: function () { }
  104096. };
  104097. }
  104098. if (typeof Blob === "undefined") {
  104099. Blob = function () { };
  104100. }
  104101. return _this;
  104102. }
  104103. NullEngine.prototype.isDeterministicLockStep = function () {
  104104. return this._options.deterministicLockstep;
  104105. };
  104106. NullEngine.prototype.getLockstepMaxSteps = function () {
  104107. return this._options.lockstepMaxSteps;
  104108. };
  104109. NullEngine.prototype.getHardwareScalingLevel = function () {
  104110. return 1.0;
  104111. };
  104112. NullEngine.prototype.createVertexBuffer = function (vertices) {
  104113. return {
  104114. capacity: 0,
  104115. references: 1,
  104116. is32Bits: false
  104117. };
  104118. };
  104119. NullEngine.prototype.createIndexBuffer = function (indices) {
  104120. return {
  104121. capacity: 0,
  104122. references: 1,
  104123. is32Bits: false
  104124. };
  104125. };
  104126. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  104127. if (stencil === void 0) { stencil = false; }
  104128. };
  104129. NullEngine.prototype.getRenderWidth = function (useScreen) {
  104130. if (useScreen === void 0) { useScreen = false; }
  104131. if (!useScreen && this._currentRenderTarget) {
  104132. return this._currentRenderTarget.width;
  104133. }
  104134. return this._options.renderWidth;
  104135. };
  104136. NullEngine.prototype.getRenderHeight = function (useScreen) {
  104137. if (useScreen === void 0) { useScreen = false; }
  104138. if (!useScreen && this._currentRenderTarget) {
  104139. return this._currentRenderTarget.height;
  104140. }
  104141. return this._options.renderHeight;
  104142. };
  104143. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  104144. this._cachedViewport = viewport;
  104145. };
  104146. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  104147. return {
  104148. transformFeedback: null,
  104149. __SPECTOR_rebuildProgram: null
  104150. };
  104151. };
  104152. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  104153. return [];
  104154. };
  104155. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  104156. return [];
  104157. };
  104158. NullEngine.prototype.bindSamplers = function (effect) {
  104159. this._currentEffect = null;
  104160. };
  104161. NullEngine.prototype.enableEffect = function (effect) {
  104162. this._currentEffect = effect;
  104163. if (effect.onBind) {
  104164. effect.onBind(effect);
  104165. }
  104166. if (effect._onBindObservable) {
  104167. effect._onBindObservable.notifyObservers(effect);
  104168. }
  104169. };
  104170. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  104171. if (zOffset === void 0) { zOffset = 0; }
  104172. if (reverseSide === void 0) { reverseSide = false; }
  104173. };
  104174. NullEngine.prototype.setIntArray = function (uniform, array) {
  104175. };
  104176. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  104177. };
  104178. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  104179. };
  104180. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  104181. };
  104182. NullEngine.prototype.setFloatArray = function (uniform, array) {
  104183. };
  104184. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  104185. };
  104186. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  104187. };
  104188. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  104189. };
  104190. NullEngine.prototype.setArray = function (uniform, array) {
  104191. };
  104192. NullEngine.prototype.setArray2 = function (uniform, array) {
  104193. };
  104194. NullEngine.prototype.setArray3 = function (uniform, array) {
  104195. };
  104196. NullEngine.prototype.setArray4 = function (uniform, array) {
  104197. };
  104198. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  104199. };
  104200. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  104201. };
  104202. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  104203. };
  104204. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  104205. };
  104206. NullEngine.prototype.setFloat = function (uniform, value) {
  104207. };
  104208. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  104209. };
  104210. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  104211. };
  104212. NullEngine.prototype.setBool = function (uniform, bool) {
  104213. };
  104214. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  104215. };
  104216. NullEngine.prototype.setColor3 = function (uniform, color3) {
  104217. };
  104218. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  104219. };
  104220. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  104221. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  104222. if (this._alphaMode === mode) {
  104223. return;
  104224. }
  104225. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  104226. if (!noDepthWriteChange) {
  104227. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  104228. }
  104229. this._alphaMode = mode;
  104230. };
  104231. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  104232. };
  104233. NullEngine.prototype.wipeCaches = function (bruteForce) {
  104234. if (this.preventCacheWipeBetweenFrames) {
  104235. return;
  104236. }
  104237. this.resetTextureCache();
  104238. this._currentEffect = null;
  104239. if (bruteForce) {
  104240. this._currentProgram = null;
  104241. this._stencilState.reset();
  104242. this._depthCullingState.reset();
  104243. this._alphaState.reset();
  104244. }
  104245. this._cachedVertexBuffers = null;
  104246. this._cachedIndexBuffer = null;
  104247. this._cachedEffectForVertexBuffers = null;
  104248. };
  104249. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  104250. };
  104251. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  104252. };
  104253. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  104254. };
  104255. /** @hidden */
  104256. NullEngine.prototype._createTexture = function () {
  104257. return {};
  104258. };
  104259. /** @hidden */
  104260. NullEngine.prototype._releaseTexture = function (texture) {
  104261. };
  104262. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  104263. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  104264. if (onLoad === void 0) { onLoad = null; }
  104265. if (onError === void 0) { onError = null; }
  104266. if (buffer === void 0) { buffer = null; }
  104267. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  104268. var url = String(urlArg);
  104269. texture.url = url;
  104270. texture.generateMipMaps = !noMipmap;
  104271. texture.samplingMode = samplingMode;
  104272. texture.invertY = invertY;
  104273. texture.baseWidth = this._options.textureSize;
  104274. texture.baseHeight = this._options.textureSize;
  104275. texture.width = this._options.textureSize;
  104276. texture.height = this._options.textureSize;
  104277. if (format) {
  104278. texture.format = format;
  104279. }
  104280. texture.isReady = true;
  104281. if (onLoad) {
  104282. onLoad();
  104283. }
  104284. this._internalTexturesCache.push(texture);
  104285. return texture;
  104286. };
  104287. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  104288. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  104289. if (options !== undefined && typeof options === "object") {
  104290. fullOptions.generateMipMaps = options.generateMipMaps;
  104291. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  104292. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  104293. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  104294. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  104295. }
  104296. else {
  104297. fullOptions.generateMipMaps = options;
  104298. fullOptions.generateDepthBuffer = true;
  104299. fullOptions.generateStencilBuffer = false;
  104300. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  104301. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  104302. }
  104303. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  104304. var width = size.width || size;
  104305. var height = size.height || size;
  104306. texture._depthStencilBuffer = {};
  104307. texture._framebuffer = {};
  104308. texture.baseWidth = width;
  104309. texture.baseHeight = height;
  104310. texture.width = width;
  104311. texture.height = height;
  104312. texture.isReady = true;
  104313. texture.samples = 1;
  104314. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  104315. texture.samplingMode = fullOptions.samplingMode;
  104316. texture.type = fullOptions.type;
  104317. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  104318. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  104319. this._internalTexturesCache.push(texture);
  104320. return texture;
  104321. };
  104322. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  104323. texture.samplingMode = samplingMode;
  104324. };
  104325. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  104326. if (this._currentRenderTarget) {
  104327. this.unBindFramebuffer(this._currentRenderTarget);
  104328. }
  104329. this._currentRenderTarget = texture;
  104330. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  104331. if (this._cachedViewport && !forceFullscreenViewport) {
  104332. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  104333. }
  104334. };
  104335. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  104336. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  104337. this._currentRenderTarget = null;
  104338. if (onBeforeUnbind) {
  104339. if (texture._MSAAFramebuffer) {
  104340. this._currentFramebuffer = texture._framebuffer;
  104341. }
  104342. onBeforeUnbind();
  104343. }
  104344. this._currentFramebuffer = null;
  104345. };
  104346. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  104347. var vbo = {
  104348. capacity: 1,
  104349. references: 1,
  104350. is32Bits: false
  104351. };
  104352. return vbo;
  104353. };
  104354. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  104355. if (premulAlpha === void 0) { premulAlpha = false; }
  104356. };
  104357. /**
  104358. * @hidden
  104359. * Get the current error code of the webGL context
  104360. * @returns the error code
  104361. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  104362. */
  104363. NullEngine.prototype.getError = function () {
  104364. return 0;
  104365. };
  104366. /** @hidden */
  104367. NullEngine.prototype._getUnpackAlignement = function () {
  104368. return 1;
  104369. };
  104370. /** @hidden */
  104371. NullEngine.prototype._unpackFlipY = function (value) {
  104372. };
  104373. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  104374. if (offset === void 0) { offset = 0; }
  104375. };
  104376. /**
  104377. * Updates a dynamic vertex buffer.
  104378. * @param vertexBuffer the vertex buffer to update
  104379. * @param data the data used to update the vertex buffer
  104380. * @param byteOffset the byte offset of the data (optional)
  104381. * @param byteLength the byte length of the data (optional)
  104382. */
  104383. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  104384. };
  104385. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  104386. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  104387. this._boundTexturesCache[this._activeChannel] = texture;
  104388. return true;
  104389. }
  104390. return false;
  104391. };
  104392. /** @hidden */
  104393. NullEngine.prototype._bindTexture = function (channel, texture) {
  104394. if (channel < 0) {
  104395. return;
  104396. }
  104397. this._bindTextureDirectly(0, texture);
  104398. };
  104399. /** @hidden */
  104400. NullEngine.prototype._releaseBuffer = function (buffer) {
  104401. buffer.references--;
  104402. if (buffer.references === 0) {
  104403. return true;
  104404. }
  104405. return false;
  104406. };
  104407. NullEngine.prototype.releaseEffects = function () {
  104408. };
  104409. NullEngine.prototype.displayLoadingUI = function () {
  104410. };
  104411. NullEngine.prototype.hideLoadingUI = function () {
  104412. };
  104413. /** @hidden */
  104414. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  104415. if (faceIndex === void 0) { faceIndex = 0; }
  104416. if (lod === void 0) { lod = 0; }
  104417. };
  104418. /** @hidden */
  104419. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  104420. if (faceIndex === void 0) { faceIndex = 0; }
  104421. if (lod === void 0) { lod = 0; }
  104422. };
  104423. /** @hidden */
  104424. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  104425. if (faceIndex === void 0) { faceIndex = 0; }
  104426. if (lod === void 0) { lod = 0; }
  104427. };
  104428. /** @hidden */
  104429. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  104430. if (faceIndex === void 0) { faceIndex = 0; }
  104431. if (lod === void 0) { lod = 0; }
  104432. };
  104433. return NullEngine;
  104434. }(BABYLON.Engine));
  104435. BABYLON.NullEngine = NullEngine;
  104436. })(BABYLON || (BABYLON = {}));
  104437. //# sourceMappingURL=babylon.nullEngine.js.map
  104438. var BABYLON;
  104439. (function (BABYLON) {
  104440. /**
  104441. * This class can be used to get instrumentation data from a Babylon engine
  104442. */
  104443. var EngineInstrumentation = /** @class */ (function () {
  104444. function EngineInstrumentation(engine) {
  104445. this.engine = engine;
  104446. this._captureGPUFrameTime = false;
  104447. this._gpuFrameTime = new BABYLON.PerfCounter();
  104448. this._captureShaderCompilationTime = false;
  104449. this._shaderCompilationTime = new BABYLON.PerfCounter();
  104450. // Observers
  104451. this._onBeginFrameObserver = null;
  104452. this._onEndFrameObserver = null;
  104453. this._onBeforeShaderCompilationObserver = null;
  104454. this._onAfterShaderCompilationObserver = null;
  104455. }
  104456. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  104457. // Properties
  104458. /**
  104459. * Gets the perf counter used for GPU frame time
  104460. */
  104461. get: function () {
  104462. return this._gpuFrameTime;
  104463. },
  104464. enumerable: true,
  104465. configurable: true
  104466. });
  104467. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  104468. /**
  104469. * Gets the GPU frame time capture status
  104470. */
  104471. get: function () {
  104472. return this._captureGPUFrameTime;
  104473. },
  104474. /**
  104475. * Enable or disable the GPU frame time capture
  104476. */
  104477. set: function (value) {
  104478. var _this = this;
  104479. if (value === this._captureGPUFrameTime) {
  104480. return;
  104481. }
  104482. this._captureGPUFrameTime = value;
  104483. if (value) {
  104484. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  104485. if (!_this._gpuFrameTimeToken) {
  104486. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  104487. }
  104488. });
  104489. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  104490. if (!_this._gpuFrameTimeToken) {
  104491. return;
  104492. }
  104493. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  104494. if (time > -1) {
  104495. _this._gpuFrameTimeToken = null;
  104496. _this._gpuFrameTime.fetchNewFrame();
  104497. _this._gpuFrameTime.addCount(time, true);
  104498. }
  104499. });
  104500. }
  104501. else {
  104502. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  104503. this._onBeginFrameObserver = null;
  104504. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  104505. this._onEndFrameObserver = null;
  104506. }
  104507. },
  104508. enumerable: true,
  104509. configurable: true
  104510. });
  104511. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  104512. /**
  104513. * Gets the perf counter used for shader compilation time
  104514. */
  104515. get: function () {
  104516. return this._shaderCompilationTime;
  104517. },
  104518. enumerable: true,
  104519. configurable: true
  104520. });
  104521. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  104522. /**
  104523. * Gets the shader compilation time capture status
  104524. */
  104525. get: function () {
  104526. return this._captureShaderCompilationTime;
  104527. },
  104528. /**
  104529. * Enable or disable the shader compilation time capture
  104530. */
  104531. set: function (value) {
  104532. var _this = this;
  104533. if (value === this._captureShaderCompilationTime) {
  104534. return;
  104535. }
  104536. this._captureShaderCompilationTime = value;
  104537. if (value) {
  104538. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  104539. _this._shaderCompilationTime.fetchNewFrame();
  104540. _this._shaderCompilationTime.beginMonitoring();
  104541. });
  104542. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  104543. _this._shaderCompilationTime.endMonitoring();
  104544. });
  104545. }
  104546. else {
  104547. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  104548. this._onBeforeShaderCompilationObserver = null;
  104549. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  104550. this._onAfterShaderCompilationObserver = null;
  104551. }
  104552. },
  104553. enumerable: true,
  104554. configurable: true
  104555. });
  104556. EngineInstrumentation.prototype.dispose = function () {
  104557. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  104558. this._onBeginFrameObserver = null;
  104559. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  104560. this._onEndFrameObserver = null;
  104561. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  104562. this._onBeforeShaderCompilationObserver = null;
  104563. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  104564. this._onAfterShaderCompilationObserver = null;
  104565. this.engine = null;
  104566. };
  104567. return EngineInstrumentation;
  104568. }());
  104569. BABYLON.EngineInstrumentation = EngineInstrumentation;
  104570. })(BABYLON || (BABYLON = {}));
  104571. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  104572. var BABYLON;
  104573. (function (BABYLON) {
  104574. /**
  104575. * This class can be used to get instrumentation data from a Babylon engine
  104576. */
  104577. var SceneInstrumentation = /** @class */ (function () {
  104578. function SceneInstrumentation(scene) {
  104579. var _this = this;
  104580. this.scene = scene;
  104581. this._captureActiveMeshesEvaluationTime = false;
  104582. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  104583. this._captureRenderTargetsRenderTime = false;
  104584. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  104585. this._captureFrameTime = false;
  104586. this._frameTime = new BABYLON.PerfCounter();
  104587. this._captureRenderTime = false;
  104588. this._renderTime = new BABYLON.PerfCounter();
  104589. this._captureInterFrameTime = false;
  104590. this._interFrameTime = new BABYLON.PerfCounter();
  104591. this._captureParticlesRenderTime = false;
  104592. this._particlesRenderTime = new BABYLON.PerfCounter();
  104593. this._captureSpritesRenderTime = false;
  104594. this._spritesRenderTime = new BABYLON.PerfCounter();
  104595. this._capturePhysicsTime = false;
  104596. this._physicsTime = new BABYLON.PerfCounter();
  104597. this._captureAnimationsTime = false;
  104598. this._animationsTime = new BABYLON.PerfCounter();
  104599. this._captureCameraRenderTime = false;
  104600. this._cameraRenderTime = new BABYLON.PerfCounter();
  104601. // Observers
  104602. this._onBeforeActiveMeshesEvaluationObserver = null;
  104603. this._onAfterActiveMeshesEvaluationObserver = null;
  104604. this._onBeforeRenderTargetsRenderObserver = null;
  104605. this._onAfterRenderTargetsRenderObserver = null;
  104606. this._onAfterRenderObserver = null;
  104607. this._onBeforeDrawPhaseObserver = null;
  104608. this._onAfterDrawPhaseObserver = null;
  104609. this._onBeforeAnimationsObserver = null;
  104610. this._onBeforeParticlesRenderingObserver = null;
  104611. this._onAfterParticlesRenderingObserver = null;
  104612. this._onBeforeSpritesRenderingObserver = null;
  104613. this._onAfterSpritesRenderingObserver = null;
  104614. this._onBeforePhysicsObserver = null;
  104615. this._onAfterPhysicsObserver = null;
  104616. this._onAfterAnimationsObserver = null;
  104617. this._onBeforeCameraRenderObserver = null;
  104618. this._onAfterCameraRenderObserver = null;
  104619. // Before render
  104620. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  104621. if (_this._captureActiveMeshesEvaluationTime) {
  104622. _this._activeMeshesEvaluationTime.fetchNewFrame();
  104623. }
  104624. if (_this._captureRenderTargetsRenderTime) {
  104625. _this._renderTargetsRenderTime.fetchNewFrame();
  104626. }
  104627. if (_this._captureFrameTime) {
  104628. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  104629. _this._frameTime.beginMonitoring();
  104630. }
  104631. if (_this._captureInterFrameTime) {
  104632. _this._interFrameTime.endMonitoring();
  104633. }
  104634. if (_this._captureParticlesRenderTime) {
  104635. _this._particlesRenderTime.fetchNewFrame();
  104636. }
  104637. if (_this._captureSpritesRenderTime) {
  104638. _this._spritesRenderTime.fetchNewFrame();
  104639. }
  104640. if (_this._captureAnimationsTime) {
  104641. _this._animationsTime.beginMonitoring();
  104642. }
  104643. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  104644. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  104645. });
  104646. // After render
  104647. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  104648. if (_this._captureFrameTime) {
  104649. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  104650. _this._frameTime.endMonitoring();
  104651. }
  104652. if (_this._captureRenderTime) {
  104653. _this._renderTime.endMonitoring(false);
  104654. }
  104655. if (_this._captureInterFrameTime) {
  104656. _this._interFrameTime.beginMonitoring();
  104657. }
  104658. });
  104659. }
  104660. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  104661. // Properties
  104662. /**
  104663. * Gets the perf counter used for active meshes evaluation time
  104664. */
  104665. get: function () {
  104666. return this._activeMeshesEvaluationTime;
  104667. },
  104668. enumerable: true,
  104669. configurable: true
  104670. });
  104671. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  104672. /**
  104673. * Gets the active meshes evaluation time capture status
  104674. */
  104675. get: function () {
  104676. return this._captureActiveMeshesEvaluationTime;
  104677. },
  104678. /**
  104679. * Enable or disable the active meshes evaluation time capture
  104680. */
  104681. set: function (value) {
  104682. var _this = this;
  104683. if (value === this._captureActiveMeshesEvaluationTime) {
  104684. return;
  104685. }
  104686. this._captureActiveMeshesEvaluationTime = value;
  104687. if (value) {
  104688. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  104689. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  104690. _this._activeMeshesEvaluationTime.beginMonitoring();
  104691. });
  104692. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  104693. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  104694. _this._activeMeshesEvaluationTime.endMonitoring();
  104695. });
  104696. }
  104697. else {
  104698. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  104699. this._onBeforeActiveMeshesEvaluationObserver = null;
  104700. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  104701. this._onAfterActiveMeshesEvaluationObserver = null;
  104702. }
  104703. },
  104704. enumerable: true,
  104705. configurable: true
  104706. });
  104707. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  104708. /**
  104709. * Gets the perf counter used for render targets render time
  104710. */
  104711. get: function () {
  104712. return this._renderTargetsRenderTime;
  104713. },
  104714. enumerable: true,
  104715. configurable: true
  104716. });
  104717. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  104718. /**
  104719. * Gets the render targets render time capture status
  104720. */
  104721. get: function () {
  104722. return this._captureRenderTargetsRenderTime;
  104723. },
  104724. /**
  104725. * Enable or disable the render targets render time capture
  104726. */
  104727. set: function (value) {
  104728. var _this = this;
  104729. if (value === this._captureRenderTargetsRenderTime) {
  104730. return;
  104731. }
  104732. this._captureRenderTargetsRenderTime = value;
  104733. if (value) {
  104734. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  104735. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  104736. _this._renderTargetsRenderTime.beginMonitoring();
  104737. });
  104738. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  104739. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  104740. _this._renderTargetsRenderTime.endMonitoring(false);
  104741. });
  104742. }
  104743. else {
  104744. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  104745. this._onBeforeRenderTargetsRenderObserver = null;
  104746. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  104747. this._onAfterRenderTargetsRenderObserver = null;
  104748. }
  104749. },
  104750. enumerable: true,
  104751. configurable: true
  104752. });
  104753. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  104754. /**
  104755. * Gets the perf counter used for particles render time
  104756. */
  104757. get: function () {
  104758. return this._particlesRenderTime;
  104759. },
  104760. enumerable: true,
  104761. configurable: true
  104762. });
  104763. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  104764. /**
  104765. * Gets the particles render time capture status
  104766. */
  104767. get: function () {
  104768. return this._captureParticlesRenderTime;
  104769. },
  104770. /**
  104771. * Enable or disable the particles render time capture
  104772. */
  104773. set: function (value) {
  104774. var _this = this;
  104775. if (value === this._captureParticlesRenderTime) {
  104776. return;
  104777. }
  104778. this._captureParticlesRenderTime = value;
  104779. if (value) {
  104780. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  104781. BABYLON.Tools.StartPerformanceCounter("Particles");
  104782. _this._particlesRenderTime.beginMonitoring();
  104783. });
  104784. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  104785. BABYLON.Tools.EndPerformanceCounter("Particles");
  104786. _this._particlesRenderTime.endMonitoring(false);
  104787. });
  104788. }
  104789. else {
  104790. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  104791. this._onBeforeParticlesRenderingObserver = null;
  104792. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  104793. this._onAfterParticlesRenderingObserver = null;
  104794. }
  104795. },
  104796. enumerable: true,
  104797. configurable: true
  104798. });
  104799. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  104800. /**
  104801. * Gets the perf counter used for sprites render time
  104802. */
  104803. get: function () {
  104804. return this._spritesRenderTime;
  104805. },
  104806. enumerable: true,
  104807. configurable: true
  104808. });
  104809. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  104810. /**
  104811. * Gets the sprites render time capture status
  104812. */
  104813. get: function () {
  104814. return this._captureSpritesRenderTime;
  104815. },
  104816. /**
  104817. * Enable or disable the sprites render time capture
  104818. */
  104819. set: function (value) {
  104820. var _this = this;
  104821. if (value === this._captureSpritesRenderTime) {
  104822. return;
  104823. }
  104824. this._captureSpritesRenderTime = value;
  104825. if (value) {
  104826. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  104827. BABYLON.Tools.StartPerformanceCounter("Sprites");
  104828. _this._spritesRenderTime.beginMonitoring();
  104829. });
  104830. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  104831. BABYLON.Tools.EndPerformanceCounter("Sprites");
  104832. _this._spritesRenderTime.endMonitoring(false);
  104833. });
  104834. }
  104835. else {
  104836. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  104837. this._onBeforeSpritesRenderingObserver = null;
  104838. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  104839. this._onAfterSpritesRenderingObserver = null;
  104840. }
  104841. },
  104842. enumerable: true,
  104843. configurable: true
  104844. });
  104845. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  104846. /**
  104847. * Gets the perf counter used for physics time
  104848. */
  104849. get: function () {
  104850. return this._physicsTime;
  104851. },
  104852. enumerable: true,
  104853. configurable: true
  104854. });
  104855. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  104856. /**
  104857. * Gets the physics time capture status
  104858. */
  104859. get: function () {
  104860. return this._capturePhysicsTime;
  104861. },
  104862. /**
  104863. * Enable or disable the physics time capture
  104864. */
  104865. set: function (value) {
  104866. var _this = this;
  104867. if (value === this._capturePhysicsTime) {
  104868. return;
  104869. }
  104870. this._capturePhysicsTime = value;
  104871. if (value) {
  104872. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  104873. BABYLON.Tools.StartPerformanceCounter("Physics");
  104874. _this._physicsTime.beginMonitoring();
  104875. });
  104876. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  104877. BABYLON.Tools.EndPerformanceCounter("Physics");
  104878. _this._physicsTime.endMonitoring();
  104879. });
  104880. }
  104881. else {
  104882. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  104883. this._onBeforePhysicsObserver = null;
  104884. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  104885. this._onAfterPhysicsObserver = null;
  104886. }
  104887. },
  104888. enumerable: true,
  104889. configurable: true
  104890. });
  104891. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  104892. /**
  104893. * Gets the perf counter used for animations time
  104894. */
  104895. get: function () {
  104896. return this._animationsTime;
  104897. },
  104898. enumerable: true,
  104899. configurable: true
  104900. });
  104901. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  104902. /**
  104903. * Gets the animations time capture status
  104904. */
  104905. get: function () {
  104906. return this._captureAnimationsTime;
  104907. },
  104908. /**
  104909. * Enable or disable the animations time capture
  104910. */
  104911. set: function (value) {
  104912. var _this = this;
  104913. if (value === this._captureAnimationsTime) {
  104914. return;
  104915. }
  104916. this._captureAnimationsTime = value;
  104917. if (value) {
  104918. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  104919. _this._animationsTime.endMonitoring();
  104920. });
  104921. }
  104922. else {
  104923. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  104924. this._onAfterAnimationsObserver = null;
  104925. }
  104926. },
  104927. enumerable: true,
  104928. configurable: true
  104929. });
  104930. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  104931. /**
  104932. * Gets the perf counter used for frame time capture
  104933. */
  104934. get: function () {
  104935. return this._frameTime;
  104936. },
  104937. enumerable: true,
  104938. configurable: true
  104939. });
  104940. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  104941. /**
  104942. * Gets the frame time capture status
  104943. */
  104944. get: function () {
  104945. return this._captureFrameTime;
  104946. },
  104947. /**
  104948. * Enable or disable the frame time capture
  104949. */
  104950. set: function (value) {
  104951. this._captureFrameTime = value;
  104952. },
  104953. enumerable: true,
  104954. configurable: true
  104955. });
  104956. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  104957. /**
  104958. * Gets the perf counter used for inter-frames time capture
  104959. */
  104960. get: function () {
  104961. return this._interFrameTime;
  104962. },
  104963. enumerable: true,
  104964. configurable: true
  104965. });
  104966. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  104967. /**
  104968. * Gets the inter-frames time capture status
  104969. */
  104970. get: function () {
  104971. return this._captureInterFrameTime;
  104972. },
  104973. /**
  104974. * Enable or disable the inter-frames time capture
  104975. */
  104976. set: function (value) {
  104977. this._captureInterFrameTime = value;
  104978. },
  104979. enumerable: true,
  104980. configurable: true
  104981. });
  104982. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  104983. /**
  104984. * Gets the perf counter used for render time capture
  104985. */
  104986. get: function () {
  104987. return this._renderTime;
  104988. },
  104989. enumerable: true,
  104990. configurable: true
  104991. });
  104992. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  104993. /**
  104994. * Gets the render time capture status
  104995. */
  104996. get: function () {
  104997. return this._captureRenderTime;
  104998. },
  104999. /**
  105000. * Enable or disable the render time capture
  105001. */
  105002. set: function (value) {
  105003. var _this = this;
  105004. if (value === this._captureRenderTime) {
  105005. return;
  105006. }
  105007. this._captureRenderTime = value;
  105008. if (value) {
  105009. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  105010. _this._renderTime.beginMonitoring();
  105011. BABYLON.Tools.StartPerformanceCounter("Main render");
  105012. });
  105013. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  105014. _this._renderTime.endMonitoring(false);
  105015. BABYLON.Tools.EndPerformanceCounter("Main render");
  105016. });
  105017. }
  105018. else {
  105019. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  105020. this._onBeforeDrawPhaseObserver = null;
  105021. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  105022. this._onAfterDrawPhaseObserver = null;
  105023. }
  105024. },
  105025. enumerable: true,
  105026. configurable: true
  105027. });
  105028. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  105029. /**
  105030. * Gets the perf counter used for camera render time capture
  105031. */
  105032. get: function () {
  105033. return this._cameraRenderTime;
  105034. },
  105035. enumerable: true,
  105036. configurable: true
  105037. });
  105038. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  105039. /**
  105040. * Gets the camera render time capture status
  105041. */
  105042. get: function () {
  105043. return this._captureCameraRenderTime;
  105044. },
  105045. /**
  105046. * Enable or disable the camera render time capture
  105047. */
  105048. set: function (value) {
  105049. var _this = this;
  105050. if (value === this._captureCameraRenderTime) {
  105051. return;
  105052. }
  105053. this._captureCameraRenderTime = value;
  105054. if (value) {
  105055. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  105056. _this._cameraRenderTime.beginMonitoring();
  105057. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  105058. });
  105059. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  105060. _this._cameraRenderTime.endMonitoring(false);
  105061. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  105062. });
  105063. }
  105064. else {
  105065. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  105066. this._onBeforeCameraRenderObserver = null;
  105067. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  105068. this._onAfterCameraRenderObserver = null;
  105069. }
  105070. },
  105071. enumerable: true,
  105072. configurable: true
  105073. });
  105074. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  105075. /**
  105076. * Gets the perf counter used for draw calls
  105077. */
  105078. get: function () {
  105079. return this.scene.getEngine()._drawCalls;
  105080. },
  105081. enumerable: true,
  105082. configurable: true
  105083. });
  105084. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  105085. /**
  105086. * Gets the perf counter used for texture collisions
  105087. */
  105088. get: function () {
  105089. return this.scene.getEngine()._textureCollisions;
  105090. },
  105091. enumerable: true,
  105092. configurable: true
  105093. });
  105094. SceneInstrumentation.prototype.dispose = function () {
  105095. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  105096. this._onAfterRenderObserver = null;
  105097. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  105098. this._onBeforeActiveMeshesEvaluationObserver = null;
  105099. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  105100. this._onAfterActiveMeshesEvaluationObserver = null;
  105101. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  105102. this._onBeforeRenderTargetsRenderObserver = null;
  105103. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  105104. this._onAfterRenderTargetsRenderObserver = null;
  105105. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  105106. this._onBeforeAnimationsObserver = null;
  105107. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  105108. this._onBeforeParticlesRenderingObserver = null;
  105109. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  105110. this._onAfterParticlesRenderingObserver = null;
  105111. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  105112. this._onBeforeSpritesRenderingObserver = null;
  105113. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  105114. this._onAfterSpritesRenderingObserver = null;
  105115. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  105116. this._onBeforeDrawPhaseObserver = null;
  105117. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  105118. this._onAfterDrawPhaseObserver = null;
  105119. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  105120. this._onBeforePhysicsObserver = null;
  105121. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  105122. this._onAfterPhysicsObserver = null;
  105123. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  105124. this._onAfterAnimationsObserver = null;
  105125. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  105126. this._onBeforeCameraRenderObserver = null;
  105127. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  105128. this._onAfterCameraRenderObserver = null;
  105129. this.scene = null;
  105130. };
  105131. return SceneInstrumentation;
  105132. }());
  105133. BABYLON.SceneInstrumentation = SceneInstrumentation;
  105134. })(BABYLON || (BABYLON = {}));
  105135. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  105136. var BABYLON;
  105137. (function (BABYLON) {
  105138. /**
  105139. * @hidden
  105140. **/
  105141. var _TimeToken = /** @class */ (function () {
  105142. function _TimeToken() {
  105143. this._timeElapsedQueryEnded = false;
  105144. }
  105145. return _TimeToken;
  105146. }());
  105147. BABYLON._TimeToken = _TimeToken;
  105148. })(BABYLON || (BABYLON = {}));
  105149. //# sourceMappingURL=babylon.timeToken.js.map
  105150. var BABYLON;
  105151. (function (BABYLON) {
  105152. /**
  105153. * Background material defines definition.
  105154. * @hidden Mainly internal Use
  105155. */
  105156. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  105157. __extends(BackgroundMaterialDefines, _super);
  105158. /**
  105159. * Constructor of the defines.
  105160. */
  105161. function BackgroundMaterialDefines() {
  105162. var _this = _super.call(this) || this;
  105163. /**
  105164. * True if the diffuse texture is in use.
  105165. */
  105166. _this.DIFFUSE = false;
  105167. /**
  105168. * The direct UV channel to use.
  105169. */
  105170. _this.DIFFUSEDIRECTUV = 0;
  105171. /**
  105172. * True if the diffuse texture is in gamma space.
  105173. */
  105174. _this.GAMMADIFFUSE = false;
  105175. /**
  105176. * True if the diffuse texture has opacity in the alpha channel.
  105177. */
  105178. _this.DIFFUSEHASALPHA = false;
  105179. /**
  105180. * True if you want the material to fade to transparent at grazing angle.
  105181. */
  105182. _this.OPACITYFRESNEL = false;
  105183. /**
  105184. * True if an extra blur needs to be added in the reflection.
  105185. */
  105186. _this.REFLECTIONBLUR = false;
  105187. /**
  105188. * True if you want the material to fade to reflection at grazing angle.
  105189. */
  105190. _this.REFLECTIONFRESNEL = false;
  105191. /**
  105192. * True if you want the material to falloff as far as you move away from the scene center.
  105193. */
  105194. _this.REFLECTIONFALLOFF = false;
  105195. /**
  105196. * False if the current Webgl implementation does not support the texture lod extension.
  105197. */
  105198. _this.TEXTURELODSUPPORT = false;
  105199. /**
  105200. * True to ensure the data are premultiplied.
  105201. */
  105202. _this.PREMULTIPLYALPHA = false;
  105203. /**
  105204. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  105205. */
  105206. _this.USERGBCOLOR = false;
  105207. /**
  105208. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  105209. * stays aligned with the desired configuration.
  105210. */
  105211. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  105212. /**
  105213. * True to add noise in order to reduce the banding effect.
  105214. */
  105215. _this.NOISE = false;
  105216. /**
  105217. * is the reflection texture in BGR color scheme?
  105218. * Mainly used to solve a bug in ios10 video tag
  105219. */
  105220. _this.REFLECTIONBGR = false;
  105221. _this.IMAGEPROCESSING = false;
  105222. _this.VIGNETTE = false;
  105223. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  105224. _this.VIGNETTEBLENDMODEOPAQUE = false;
  105225. _this.TONEMAPPING = false;
  105226. _this.TONEMAPPING_ACES = false;
  105227. _this.CONTRAST = false;
  105228. _this.COLORCURVES = false;
  105229. _this.COLORGRADING = false;
  105230. _this.COLORGRADING3D = false;
  105231. _this.SAMPLER3DGREENDEPTH = false;
  105232. _this.SAMPLER3DBGRMAP = false;
  105233. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  105234. _this.EXPOSURE = false;
  105235. // Reflection.
  105236. _this.REFLECTION = false;
  105237. _this.REFLECTIONMAP_3D = false;
  105238. _this.REFLECTIONMAP_SPHERICAL = false;
  105239. _this.REFLECTIONMAP_PLANAR = false;
  105240. _this.REFLECTIONMAP_CUBIC = false;
  105241. _this.REFLECTIONMAP_PROJECTION = false;
  105242. _this.REFLECTIONMAP_SKYBOX = false;
  105243. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  105244. _this.REFLECTIONMAP_EXPLICIT = false;
  105245. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  105246. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  105247. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  105248. _this.INVERTCUBICMAP = false;
  105249. _this.REFLECTIONMAP_OPPOSITEZ = false;
  105250. _this.LODINREFLECTIONALPHA = false;
  105251. _this.GAMMAREFLECTION = false;
  105252. _this.RGBDREFLECTION = false;
  105253. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  105254. // Default BJS.
  105255. _this.MAINUV1 = false;
  105256. _this.MAINUV2 = false;
  105257. _this.UV1 = false;
  105258. _this.UV2 = false;
  105259. _this.CLIPPLANE = false;
  105260. _this.CLIPPLANE2 = false;
  105261. _this.CLIPPLANE3 = false;
  105262. _this.CLIPPLANE4 = false;
  105263. _this.POINTSIZE = false;
  105264. _this.FOG = false;
  105265. _this.NORMAL = false;
  105266. _this.NUM_BONE_INFLUENCERS = 0;
  105267. _this.BonesPerMesh = 0;
  105268. _this.INSTANCES = false;
  105269. _this.SHADOWFLOAT = false;
  105270. _this.rebuild();
  105271. return _this;
  105272. }
  105273. return BackgroundMaterialDefines;
  105274. }(BABYLON.MaterialDefines));
  105275. /**
  105276. * Background material used to create an efficient environement around your scene.
  105277. */
  105278. var BackgroundMaterial = /** @class */ (function (_super) {
  105279. __extends(BackgroundMaterial, _super);
  105280. /**
  105281. * Instantiates a Background Material in the given scene
  105282. * @param name The friendly name of the material
  105283. * @param scene The scene to add the material to
  105284. */
  105285. function BackgroundMaterial(name, scene) {
  105286. var _this = _super.call(this, name, scene) || this;
  105287. /**
  105288. * Key light Color (multiply against the environement texture)
  105289. */
  105290. _this.primaryColor = BABYLON.Color3.White();
  105291. _this._primaryColorShadowLevel = 0;
  105292. _this._primaryColorHighlightLevel = 0;
  105293. /**
  105294. * Reflection Texture used in the material.
  105295. * Should be author in a specific way for the best result (refer to the documentation).
  105296. */
  105297. _this.reflectionTexture = null;
  105298. /**
  105299. * Reflection Texture level of blur.
  105300. *
  105301. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  105302. * texture twice.
  105303. */
  105304. _this.reflectionBlur = 0;
  105305. /**
  105306. * Diffuse Texture used in the material.
  105307. * Should be author in a specific way for the best result (refer to the documentation).
  105308. */
  105309. _this.diffuseTexture = null;
  105310. _this._shadowLights = null;
  105311. /**
  105312. * Specify the list of lights casting shadow on the material.
  105313. * All scene shadow lights will be included if null.
  105314. */
  105315. _this.shadowLights = null;
  105316. /**
  105317. * Helps adjusting the shadow to a softer level if required.
  105318. * 0 means black shadows and 1 means no shadows.
  105319. */
  105320. _this.shadowLevel = 0;
  105321. /**
  105322. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  105323. * It is usually zero but might be interesting to modify according to your setup.
  105324. */
  105325. _this.sceneCenter = BABYLON.Vector3.Zero();
  105326. /**
  105327. * This helps specifying that the material is falling off to the sky box at grazing angle.
  105328. * This helps ensuring a nice transition when the camera goes under the ground.
  105329. */
  105330. _this.opacityFresnel = true;
  105331. /**
  105332. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  105333. * This helps adding a mirror texture on the ground.
  105334. */
  105335. _this.reflectionFresnel = false;
  105336. /**
  105337. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  105338. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  105339. */
  105340. _this.reflectionFalloffDistance = 0.0;
  105341. /**
  105342. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  105343. */
  105344. _this.reflectionAmount = 1.0;
  105345. /**
  105346. * This specifies the weight of the reflection at grazing angle.
  105347. */
  105348. _this.reflectionReflectance0 = 0.05;
  105349. /**
  105350. * This specifies the weight of the reflection at a perpendicular point of view.
  105351. */
  105352. _this.reflectionReflectance90 = 0.5;
  105353. /**
  105354. * Helps to directly use the maps channels instead of their level.
  105355. */
  105356. _this.useRGBColor = true;
  105357. /**
  105358. * This helps reducing the banding effect that could occur on the background.
  105359. */
  105360. _this.enableNoise = false;
  105361. _this._fovMultiplier = 1.0;
  105362. /**
  105363. * Enable the FOV adjustment feature controlled by fovMultiplier.
  105364. */
  105365. _this.useEquirectangularFOV = false;
  105366. _this._maxSimultaneousLights = 4;
  105367. /**
  105368. * Number of Simultaneous lights allowed on the material.
  105369. */
  105370. _this.maxSimultaneousLights = 4;
  105371. /**
  105372. * Keep track of the image processing observer to allow dispose and replace.
  105373. */
  105374. _this._imageProcessingObserver = null;
  105375. /**
  105376. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  105377. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  105378. */
  105379. _this.switchToBGR = false;
  105380. // Temp values kept as cache in the material.
  105381. _this._renderTargets = new BABYLON.SmartArray(16);
  105382. _this._reflectionControls = BABYLON.Vector4.Zero();
  105383. _this._white = BABYLON.Color3.White();
  105384. _this._primaryShadowColor = BABYLON.Color3.Black();
  105385. _this._primaryHighlightColor = BABYLON.Color3.Black();
  105386. // Setup the default processing configuration to the scene.
  105387. _this._attachImageProcessingConfiguration(null);
  105388. _this.getRenderTargetTextures = function () {
  105389. _this._renderTargets.reset();
  105390. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  105391. _this._renderTargets.push(_this._diffuseTexture);
  105392. }
  105393. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  105394. _this._renderTargets.push(_this._reflectionTexture);
  105395. }
  105396. return _this._renderTargets;
  105397. };
  105398. return _this;
  105399. }
  105400. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  105401. /**
  105402. * Experimental Internal Use Only.
  105403. *
  105404. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  105405. * This acts as a helper to set the primary color to a more "human friendly" value.
  105406. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  105407. * output color as close as possible from the chosen value.
  105408. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  105409. * part of lighting setup.)
  105410. */
  105411. get: function () {
  105412. return this.__perceptualColor;
  105413. },
  105414. set: function (value) {
  105415. this.__perceptualColor = value;
  105416. this._computePrimaryColorFromPerceptualColor();
  105417. this._markAllSubMeshesAsLightsDirty();
  105418. },
  105419. enumerable: true,
  105420. configurable: true
  105421. });
  105422. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  105423. /**
  105424. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  105425. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  105426. */
  105427. get: function () {
  105428. return this._primaryColorShadowLevel;
  105429. },
  105430. set: function (value) {
  105431. this._primaryColorShadowLevel = value;
  105432. this._computePrimaryColors();
  105433. this._markAllSubMeshesAsLightsDirty();
  105434. },
  105435. enumerable: true,
  105436. configurable: true
  105437. });
  105438. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  105439. /**
  105440. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  105441. * The primary color is used at the level chosen to define what the white area would look.
  105442. */
  105443. get: function () {
  105444. return this._primaryColorHighlightLevel;
  105445. },
  105446. set: function (value) {
  105447. this._primaryColorHighlightLevel = value;
  105448. this._computePrimaryColors();
  105449. this._markAllSubMeshesAsLightsDirty();
  105450. },
  105451. enumerable: true,
  105452. configurable: true
  105453. });
  105454. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  105455. /**
  105456. * Sets the reflection reflectance fresnel values according to the default standard
  105457. * empirically know to work well :-)
  105458. */
  105459. set: function (value) {
  105460. var reflectionWeight = value;
  105461. if (reflectionWeight < 0.5) {
  105462. reflectionWeight = reflectionWeight * 2.0;
  105463. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  105464. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  105465. }
  105466. else {
  105467. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  105468. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  105469. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  105470. }
  105471. },
  105472. enumerable: true,
  105473. configurable: true
  105474. });
  105475. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  105476. /**
  105477. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  105478. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  105479. * Recommended to be keep at 1.0 except for special cases.
  105480. */
  105481. get: function () {
  105482. return this._fovMultiplier;
  105483. },
  105484. set: function (value) {
  105485. if (isNaN(value)) {
  105486. value = 1.0;
  105487. }
  105488. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  105489. },
  105490. enumerable: true,
  105491. configurable: true
  105492. });
  105493. /**
  105494. * Attaches a new image processing configuration to the PBR Material.
  105495. * @param configuration (if null the scene configuration will be use)
  105496. */
  105497. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  105498. var _this = this;
  105499. if (configuration === this._imageProcessingConfiguration) {
  105500. return;
  105501. }
  105502. // Detaches observer.
  105503. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  105504. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  105505. }
  105506. // Pick the scene configuration if needed.
  105507. if (!configuration) {
  105508. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  105509. }
  105510. else {
  105511. this._imageProcessingConfiguration = configuration;
  105512. }
  105513. // Attaches observer.
  105514. if (this._imageProcessingConfiguration) {
  105515. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  105516. _this._computePrimaryColorFromPerceptualColor();
  105517. _this._markAllSubMeshesAsImageProcessingDirty();
  105518. });
  105519. }
  105520. };
  105521. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  105522. /**
  105523. * Gets the image processing configuration used either in this material.
  105524. */
  105525. get: function () {
  105526. return this._imageProcessingConfiguration;
  105527. },
  105528. /**
  105529. * Sets the Default image processing configuration used either in the this material.
  105530. *
  105531. * If sets to null, the scene one is in use.
  105532. */
  105533. set: function (value) {
  105534. this._attachImageProcessingConfiguration(value);
  105535. // Ensure the effect will be rebuilt.
  105536. this._markAllSubMeshesAsTexturesDirty();
  105537. },
  105538. enumerable: true,
  105539. configurable: true
  105540. });
  105541. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  105542. /**
  105543. * Gets wether the color curves effect is enabled.
  105544. */
  105545. get: function () {
  105546. return this.imageProcessingConfiguration.colorCurvesEnabled;
  105547. },
  105548. /**
  105549. * Sets wether the color curves effect is enabled.
  105550. */
  105551. set: function (value) {
  105552. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  105553. },
  105554. enumerable: true,
  105555. configurable: true
  105556. });
  105557. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  105558. /**
  105559. * Gets wether the color grading effect is enabled.
  105560. */
  105561. get: function () {
  105562. return this.imageProcessingConfiguration.colorGradingEnabled;
  105563. },
  105564. /**
  105565. * Gets wether the color grading effect is enabled.
  105566. */
  105567. set: function (value) {
  105568. this.imageProcessingConfiguration.colorGradingEnabled = value;
  105569. },
  105570. enumerable: true,
  105571. configurable: true
  105572. });
  105573. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  105574. /**
  105575. * Gets wether tonemapping is enabled or not.
  105576. */
  105577. get: function () {
  105578. return this._imageProcessingConfiguration.toneMappingEnabled;
  105579. },
  105580. /**
  105581. * Sets wether tonemapping is enabled or not
  105582. */
  105583. set: function (value) {
  105584. this._imageProcessingConfiguration.toneMappingEnabled = value;
  105585. },
  105586. enumerable: true,
  105587. configurable: true
  105588. });
  105589. ;
  105590. ;
  105591. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  105592. /**
  105593. * The camera exposure used on this material.
  105594. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  105595. * This corresponds to a photographic exposure.
  105596. */
  105597. get: function () {
  105598. return this._imageProcessingConfiguration.exposure;
  105599. },
  105600. /**
  105601. * The camera exposure used on this material.
  105602. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  105603. * This corresponds to a photographic exposure.
  105604. */
  105605. set: function (value) {
  105606. this._imageProcessingConfiguration.exposure = value;
  105607. },
  105608. enumerable: true,
  105609. configurable: true
  105610. });
  105611. ;
  105612. ;
  105613. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  105614. /**
  105615. * Gets The camera contrast used on this material.
  105616. */
  105617. get: function () {
  105618. return this._imageProcessingConfiguration.contrast;
  105619. },
  105620. /**
  105621. * Sets The camera contrast used on this material.
  105622. */
  105623. set: function (value) {
  105624. this._imageProcessingConfiguration.contrast = value;
  105625. },
  105626. enumerable: true,
  105627. configurable: true
  105628. });
  105629. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  105630. /**
  105631. * Gets the Color Grading 2D Lookup Texture.
  105632. */
  105633. get: function () {
  105634. return this._imageProcessingConfiguration.colorGradingTexture;
  105635. },
  105636. /**
  105637. * Sets the Color Grading 2D Lookup Texture.
  105638. */
  105639. set: function (value) {
  105640. this.imageProcessingConfiguration.colorGradingTexture = value;
  105641. },
  105642. enumerable: true,
  105643. configurable: true
  105644. });
  105645. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  105646. /**
  105647. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  105648. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  105649. * 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;
  105650. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  105651. */
  105652. get: function () {
  105653. return this.imageProcessingConfiguration.colorCurves;
  105654. },
  105655. /**
  105656. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  105657. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  105658. * 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;
  105659. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  105660. */
  105661. set: function (value) {
  105662. this.imageProcessingConfiguration.colorCurves = value;
  105663. },
  105664. enumerable: true,
  105665. configurable: true
  105666. });
  105667. /**
  105668. * The entire material has been created in order to prevent overdraw.
  105669. * @returns false
  105670. */
  105671. BackgroundMaterial.prototype.needAlphaTesting = function () {
  105672. return true;
  105673. };
  105674. /**
  105675. * The entire material has been created in order to prevent overdraw.
  105676. * @returns true if blending is enable
  105677. */
  105678. BackgroundMaterial.prototype.needAlphaBlending = function () {
  105679. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  105680. };
  105681. /**
  105682. * Checks wether the material is ready to be rendered for a given mesh.
  105683. * @param mesh The mesh to render
  105684. * @param subMesh The submesh to check against
  105685. * @param useInstances Specify wether or not the material is used with instances
  105686. * @returns true if all the dependencies are ready (Textures, Effects...)
  105687. */
  105688. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  105689. var _this = this;
  105690. if (useInstances === void 0) { useInstances = false; }
  105691. if (subMesh.effect && this.isFrozen) {
  105692. if (this._wasPreviouslyReady) {
  105693. return true;
  105694. }
  105695. }
  105696. if (!subMesh._materialDefines) {
  105697. subMesh._materialDefines = new BackgroundMaterialDefines();
  105698. }
  105699. var scene = this.getScene();
  105700. var defines = subMesh._materialDefines;
  105701. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  105702. if (defines._renderId === scene.getRenderId()) {
  105703. return true;
  105704. }
  105705. }
  105706. var engine = scene.getEngine();
  105707. // Lights
  105708. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  105709. defines._needNormals = true;
  105710. // Textures
  105711. if (defines._areTexturesDirty) {
  105712. defines._needUVs = false;
  105713. if (scene.texturesEnabled) {
  105714. if (scene.getEngine().getCaps().textureLOD) {
  105715. defines.TEXTURELODSUPPORT = true;
  105716. }
  105717. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  105718. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  105719. return false;
  105720. }
  105721. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  105722. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  105723. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  105724. defines.OPACITYFRESNEL = this._opacityFresnel;
  105725. }
  105726. else {
  105727. defines.DIFFUSE = false;
  105728. defines.DIFFUSEHASALPHA = false;
  105729. defines.GAMMADIFFUSE = false;
  105730. defines.OPACITYFRESNEL = false;
  105731. }
  105732. var reflectionTexture = this._reflectionTexture;
  105733. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  105734. if (!reflectionTexture.isReadyOrNotBlocking()) {
  105735. return false;
  105736. }
  105737. defines.REFLECTION = true;
  105738. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  105739. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  105740. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  105741. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  105742. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  105743. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  105744. defines.REFLECTIONBGR = this.switchToBGR;
  105745. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  105746. defines.INVERTCUBICMAP = true;
  105747. }
  105748. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  105749. switch (reflectionTexture.coordinatesMode) {
  105750. case BABYLON.Texture.EXPLICIT_MODE:
  105751. defines.REFLECTIONMAP_EXPLICIT = true;
  105752. break;
  105753. case BABYLON.Texture.PLANAR_MODE:
  105754. defines.REFLECTIONMAP_PLANAR = true;
  105755. break;
  105756. case BABYLON.Texture.PROJECTION_MODE:
  105757. defines.REFLECTIONMAP_PROJECTION = true;
  105758. break;
  105759. case BABYLON.Texture.SKYBOX_MODE:
  105760. defines.REFLECTIONMAP_SKYBOX = true;
  105761. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  105762. break;
  105763. case BABYLON.Texture.SPHERICAL_MODE:
  105764. defines.REFLECTIONMAP_SPHERICAL = true;
  105765. break;
  105766. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  105767. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  105768. break;
  105769. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  105770. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  105771. break;
  105772. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  105773. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  105774. break;
  105775. case BABYLON.Texture.CUBIC_MODE:
  105776. case BABYLON.Texture.INVCUBIC_MODE:
  105777. default:
  105778. defines.REFLECTIONMAP_CUBIC = true;
  105779. break;
  105780. }
  105781. if (this.reflectionFresnel) {
  105782. defines.REFLECTIONFRESNEL = true;
  105783. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  105784. this._reflectionControls.x = this.reflectionAmount;
  105785. this._reflectionControls.y = this.reflectionReflectance0;
  105786. this._reflectionControls.z = this.reflectionReflectance90;
  105787. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  105788. }
  105789. else {
  105790. defines.REFLECTIONFRESNEL = false;
  105791. defines.REFLECTIONFALLOFF = false;
  105792. }
  105793. }
  105794. else {
  105795. defines.REFLECTION = false;
  105796. defines.REFLECTIONFRESNEL = false;
  105797. defines.REFLECTIONFALLOFF = false;
  105798. defines.REFLECTIONBLUR = false;
  105799. defines.REFLECTIONMAP_3D = false;
  105800. defines.REFLECTIONMAP_SPHERICAL = false;
  105801. defines.REFLECTIONMAP_PLANAR = false;
  105802. defines.REFLECTIONMAP_CUBIC = false;
  105803. defines.REFLECTIONMAP_PROJECTION = false;
  105804. defines.REFLECTIONMAP_SKYBOX = false;
  105805. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  105806. defines.REFLECTIONMAP_EXPLICIT = false;
  105807. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  105808. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  105809. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  105810. defines.INVERTCUBICMAP = false;
  105811. defines.REFLECTIONMAP_OPPOSITEZ = false;
  105812. defines.LODINREFLECTIONALPHA = false;
  105813. defines.GAMMAREFLECTION = false;
  105814. defines.RGBDREFLECTION = false;
  105815. }
  105816. }
  105817. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  105818. defines.USERGBCOLOR = this._useRGBColor;
  105819. defines.NOISE = this._enableNoise;
  105820. }
  105821. if (defines._areLightsDirty) {
  105822. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  105823. }
  105824. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  105825. if (!this._imageProcessingConfiguration.isReady()) {
  105826. return false;
  105827. }
  105828. this._imageProcessingConfiguration.prepareDefines(defines);
  105829. }
  105830. // Misc.
  105831. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  105832. // Values that need to be evaluated on every frame
  105833. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  105834. // Attribs
  105835. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  105836. if (mesh) {
  105837. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  105838. mesh.createNormals(true);
  105839. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  105840. }
  105841. }
  105842. }
  105843. // Get correct effect
  105844. if (defines.isDirty) {
  105845. defines.markAsProcessed();
  105846. scene.resetCachedMaterial();
  105847. // Fallbacks
  105848. var fallbacks = new BABYLON.EffectFallbacks();
  105849. if (defines.FOG) {
  105850. fallbacks.addFallback(0, "FOG");
  105851. }
  105852. if (defines.POINTSIZE) {
  105853. fallbacks.addFallback(1, "POINTSIZE");
  105854. }
  105855. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  105856. if (defines.NUM_BONE_INFLUENCERS > 0) {
  105857. fallbacks.addCPUSkinningFallback(0, mesh);
  105858. }
  105859. //Attributes
  105860. var attribs = [BABYLON.VertexBuffer.PositionKind];
  105861. if (defines.NORMAL) {
  105862. attribs.push(BABYLON.VertexBuffer.NormalKind);
  105863. }
  105864. if (defines.UV1) {
  105865. attribs.push(BABYLON.VertexBuffer.UVKind);
  105866. }
  105867. if (defines.UV2) {
  105868. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  105869. }
  105870. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  105871. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  105872. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  105873. "vFogInfos", "vFogColor", "pointSize",
  105874. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  105875. "vPrimaryColor", "vPrimaryColorShadow",
  105876. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  105877. "shadowLevel", "alpha",
  105878. "vBackgroundCenter", "vReflectionControl",
  105879. "vDiffuseInfos", "diffuseMatrix",
  105880. ];
  105881. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  105882. var uniformBuffers = ["Material", "Scene"];
  105883. if (BABYLON.ImageProcessingConfiguration) {
  105884. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  105885. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  105886. }
  105887. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  105888. uniformsNames: uniforms,
  105889. uniformBuffersNames: uniformBuffers,
  105890. samplers: samplers,
  105891. defines: defines,
  105892. maxSimultaneousLights: this._maxSimultaneousLights
  105893. });
  105894. var onCompiled = function (effect) {
  105895. if (_this.onCompiled) {
  105896. _this.onCompiled(effect);
  105897. }
  105898. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  105899. };
  105900. var join = defines.toString();
  105901. subMesh.setEffect(scene.getEngine().createEffect("background", {
  105902. attributes: attribs,
  105903. uniformsNames: uniforms,
  105904. uniformBuffersNames: uniformBuffers,
  105905. samplers: samplers,
  105906. defines: join,
  105907. fallbacks: fallbacks,
  105908. onCompiled: onCompiled,
  105909. onError: this.onError,
  105910. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  105911. }, engine), defines);
  105912. this.buildUniformLayout();
  105913. }
  105914. if (!subMesh.effect || !subMesh.effect.isReady()) {
  105915. return false;
  105916. }
  105917. defines._renderId = scene.getRenderId();
  105918. this._wasPreviouslyReady = true;
  105919. return true;
  105920. };
  105921. /**
  105922. * Compute the primary color according to the chosen perceptual color.
  105923. */
  105924. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  105925. if (!this.__perceptualColor) {
  105926. return;
  105927. }
  105928. this._primaryColor.copyFrom(this.__perceptualColor);
  105929. // Revert gamma space.
  105930. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  105931. // Revert image processing configuration.
  105932. if (this._imageProcessingConfiguration) {
  105933. // Revert Exposure.
  105934. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  105935. }
  105936. this._computePrimaryColors();
  105937. };
  105938. /**
  105939. * Compute the highlights and shadow colors according to their chosen levels.
  105940. */
  105941. BackgroundMaterial.prototype._computePrimaryColors = function () {
  105942. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  105943. return;
  105944. }
  105945. // Find the highlight color based on the configuration.
  105946. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  105947. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  105948. // Find the shadow color based on the configuration.
  105949. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  105950. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  105951. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  105952. };
  105953. /**
  105954. * Build the uniform buffer used in the material.
  105955. */
  105956. BackgroundMaterial.prototype.buildUniformLayout = function () {
  105957. // Order is important !
  105958. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  105959. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  105960. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  105961. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  105962. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  105963. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  105964. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  105965. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  105966. this._uniformBuffer.addUniform("pointSize", 1);
  105967. this._uniformBuffer.addUniform("shadowLevel", 1);
  105968. this._uniformBuffer.addUniform("alpha", 1);
  105969. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  105970. this._uniformBuffer.addUniform("vReflectionControl", 4);
  105971. this._uniformBuffer.create();
  105972. };
  105973. /**
  105974. * Unbind the material.
  105975. */
  105976. BackgroundMaterial.prototype.unbind = function () {
  105977. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  105978. this._uniformBuffer.setTexture("diffuseSampler", null);
  105979. }
  105980. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  105981. this._uniformBuffer.setTexture("reflectionSampler", null);
  105982. }
  105983. _super.prototype.unbind.call(this);
  105984. };
  105985. /**
  105986. * Bind only the world matrix to the material.
  105987. * @param world The world matrix to bind.
  105988. */
  105989. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  105990. this._activeEffect.setMatrix("world", world);
  105991. };
  105992. /**
  105993. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  105994. * @param world The world matrix to bind.
  105995. * @param subMesh The submesh to bind for.
  105996. */
  105997. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  105998. var scene = this.getScene();
  105999. var defines = subMesh._materialDefines;
  106000. if (!defines) {
  106001. return;
  106002. }
  106003. var effect = subMesh.effect;
  106004. if (!effect) {
  106005. return;
  106006. }
  106007. this._activeEffect = effect;
  106008. // Matrices
  106009. this.bindOnlyWorldMatrix(world);
  106010. // Bones
  106011. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  106012. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  106013. if (mustRebind) {
  106014. this._uniformBuffer.bindToEffect(effect, "Material");
  106015. this.bindViewProjection(effect);
  106016. var reflectionTexture = this._reflectionTexture;
  106017. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  106018. // Texture uniforms
  106019. if (scene.texturesEnabled) {
  106020. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  106021. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  106022. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  106023. }
  106024. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  106025. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  106026. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  106027. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  106028. }
  106029. }
  106030. if (this.shadowLevel > 0) {
  106031. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  106032. }
  106033. this._uniformBuffer.updateFloat("alpha", this.alpha);
  106034. // Point size
  106035. if (this.pointsCloud) {
  106036. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  106037. }
  106038. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  106039. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  106040. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  106041. }
  106042. else {
  106043. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  106044. }
  106045. }
  106046. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  106047. // Textures
  106048. if (scene.texturesEnabled) {
  106049. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  106050. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  106051. }
  106052. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  106053. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  106054. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  106055. }
  106056. else if (!defines.REFLECTIONBLUR) {
  106057. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  106058. }
  106059. else {
  106060. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  106061. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  106062. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  106063. }
  106064. if (defines.REFLECTIONFRESNEL) {
  106065. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  106066. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  106067. }
  106068. }
  106069. }
  106070. // Clip plane
  106071. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  106072. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  106073. }
  106074. if (mustRebind || !this.isFrozen) {
  106075. if (scene.lightsEnabled) {
  106076. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  106077. }
  106078. // View
  106079. this.bindView(effect);
  106080. // Fog
  106081. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  106082. // image processing
  106083. if (this._imageProcessingConfiguration) {
  106084. this._imageProcessingConfiguration.bind(this._activeEffect);
  106085. }
  106086. }
  106087. this._uniformBuffer.update();
  106088. this._afterBind(mesh, this._activeEffect);
  106089. };
  106090. /**
  106091. * Dispose the material.
  106092. * @param forceDisposeEffect Force disposal of the associated effect.
  106093. * @param forceDisposeTextures Force disposal of the associated textures.
  106094. */
  106095. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  106096. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  106097. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  106098. if (forceDisposeTextures) {
  106099. if (this.diffuseTexture) {
  106100. this.diffuseTexture.dispose();
  106101. }
  106102. if (this.reflectionTexture) {
  106103. this.reflectionTexture.dispose();
  106104. }
  106105. }
  106106. this._renderTargets.dispose();
  106107. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  106108. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  106109. }
  106110. _super.prototype.dispose.call(this, forceDisposeEffect);
  106111. };
  106112. /**
  106113. * Clones the material.
  106114. * @param name The cloned name.
  106115. * @returns The cloned material.
  106116. */
  106117. BackgroundMaterial.prototype.clone = function (name) {
  106118. var _this = this;
  106119. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  106120. };
  106121. /**
  106122. * Serializes the current material to its JSON representation.
  106123. * @returns The JSON representation.
  106124. */
  106125. BackgroundMaterial.prototype.serialize = function () {
  106126. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  106127. serializationObject.customType = "BABYLON.BackgroundMaterial";
  106128. return serializationObject;
  106129. };
  106130. /**
  106131. * Gets the class name of the material
  106132. * @returns "BackgroundMaterial"
  106133. */
  106134. BackgroundMaterial.prototype.getClassName = function () {
  106135. return "BackgroundMaterial";
  106136. };
  106137. /**
  106138. * Parse a JSON input to create back a background material.
  106139. * @param source The JSON data to parse
  106140. * @param scene The scene to create the parsed material in
  106141. * @param rootUrl The root url of the assets the material depends upon
  106142. * @returns the instantiated BackgroundMaterial.
  106143. */
  106144. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  106145. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  106146. };
  106147. /**
  106148. * Standard reflectance value at parallel view angle.
  106149. */
  106150. BackgroundMaterial.StandardReflectance0 = 0.05;
  106151. /**
  106152. * Standard reflectance value at grazing angle.
  106153. */
  106154. BackgroundMaterial.StandardReflectance90 = 0.5;
  106155. __decorate([
  106156. BABYLON.serializeAsColor3()
  106157. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  106158. __decorate([
  106159. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  106160. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  106161. __decorate([
  106162. BABYLON.serializeAsColor3()
  106163. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  106164. __decorate([
  106165. BABYLON.serialize()
  106166. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  106167. __decorate([
  106168. BABYLON.serialize()
  106169. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  106170. __decorate([
  106171. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  106172. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  106173. __decorate([
  106174. BABYLON.serializeAsTexture()
  106175. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  106176. __decorate([
  106177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106178. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  106179. __decorate([
  106180. BABYLON.serialize()
  106181. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  106182. __decorate([
  106183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106184. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  106185. __decorate([
  106186. BABYLON.serializeAsTexture()
  106187. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  106188. __decorate([
  106189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106190. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  106191. __decorate([
  106192. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106193. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  106194. __decorate([
  106195. BABYLON.serialize()
  106196. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  106197. __decorate([
  106198. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106199. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  106200. __decorate([
  106201. BABYLON.serializeAsVector3()
  106202. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  106203. __decorate([
  106204. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106205. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  106206. __decorate([
  106207. BABYLON.serialize()
  106208. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  106209. __decorate([
  106210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106211. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  106212. __decorate([
  106213. BABYLON.serialize()
  106214. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  106215. __decorate([
  106216. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106217. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  106218. __decorate([
  106219. BABYLON.serialize()
  106220. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  106221. __decorate([
  106222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106223. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  106224. __decorate([
  106225. BABYLON.serialize()
  106226. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  106227. __decorate([
  106228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106229. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  106230. __decorate([
  106231. BABYLON.serialize()
  106232. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  106233. __decorate([
  106234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106235. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  106236. __decorate([
  106237. BABYLON.serialize()
  106238. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  106239. __decorate([
  106240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106241. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  106242. __decorate([
  106243. BABYLON.serialize()
  106244. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  106245. __decorate([
  106246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106247. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  106248. __decorate([
  106249. BABYLON.serialize()
  106250. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  106251. __decorate([
  106252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106253. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  106254. __decorate([
  106255. BABYLON.serialize()
  106256. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  106257. __decorate([
  106258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106259. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  106260. __decorate([
  106261. BABYLON.serializeAsImageProcessingConfiguration()
  106262. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  106263. return BackgroundMaterial;
  106264. }(BABYLON.PushMaterial));
  106265. BABYLON.BackgroundMaterial = BackgroundMaterial;
  106266. })(BABYLON || (BABYLON = {}));
  106267. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  106268. var __assign = (this && this.__assign) || function () {
  106269. __assign = Object.assign || function(t) {
  106270. for (var s, i = 1, n = arguments.length; i < n; i++) {
  106271. s = arguments[i];
  106272. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  106273. t[p] = s[p];
  106274. }
  106275. return t;
  106276. };
  106277. return __assign.apply(this, arguments);
  106278. };
  106279. var BABYLON;
  106280. (function (BABYLON) {
  106281. /**
  106282. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  106283. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  106284. * It also helps with the default setup of your imageProcessing configuration.
  106285. */
  106286. var EnvironmentHelper = /** @class */ (function () {
  106287. /**
  106288. * constructor
  106289. * @param options
  106290. * @param scene The scene to add the material to
  106291. */
  106292. function EnvironmentHelper(options, scene) {
  106293. var _this = this;
  106294. this._errorHandler = function (message, exception) {
  106295. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  106296. };
  106297. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  106298. this._scene = scene;
  106299. this.onErrorObservable = new BABYLON.Observable();
  106300. this._setupBackground();
  106301. this._setupImageProcessing();
  106302. }
  106303. /**
  106304. * Creates the default options for the helper.
  106305. */
  106306. EnvironmentHelper._getDefaultOptions = function () {
  106307. return {
  106308. createGround: true,
  106309. groundSize: 15,
  106310. groundTexture: this._groundTextureCDNUrl,
  106311. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  106312. groundOpacity: 0.9,
  106313. enableGroundShadow: true,
  106314. groundShadowLevel: 0.5,
  106315. enableGroundMirror: false,
  106316. groundMirrorSizeRatio: 0.3,
  106317. groundMirrorBlurKernel: 64,
  106318. groundMirrorAmount: 1,
  106319. groundMirrorFresnelWeight: 1,
  106320. groundMirrorFallOffDistance: 0,
  106321. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  106322. groundYBias: 0.00001,
  106323. createSkybox: true,
  106324. skyboxSize: 20,
  106325. skyboxTexture: this._skyboxTextureCDNUrl,
  106326. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  106327. backgroundYRotation: 0,
  106328. sizeAuto: true,
  106329. rootPosition: BABYLON.Vector3.Zero(),
  106330. setupImageProcessing: true,
  106331. environmentTexture: this._environmentTextureCDNUrl,
  106332. cameraExposure: 0.8,
  106333. cameraContrast: 1.2,
  106334. toneMappingEnabled: true,
  106335. };
  106336. };
  106337. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  106338. /**
  106339. * Gets the root mesh created by the helper.
  106340. */
  106341. get: function () {
  106342. return this._rootMesh;
  106343. },
  106344. enumerable: true,
  106345. configurable: true
  106346. });
  106347. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  106348. /**
  106349. * Gets the skybox created by the helper.
  106350. */
  106351. get: function () {
  106352. return this._skybox;
  106353. },
  106354. enumerable: true,
  106355. configurable: true
  106356. });
  106357. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  106358. /**
  106359. * Gets the skybox texture created by the helper.
  106360. */
  106361. get: function () {
  106362. return this._skyboxTexture;
  106363. },
  106364. enumerable: true,
  106365. configurable: true
  106366. });
  106367. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  106368. /**
  106369. * Gets the skybox material created by the helper.
  106370. */
  106371. get: function () {
  106372. return this._skyboxMaterial;
  106373. },
  106374. enumerable: true,
  106375. configurable: true
  106376. });
  106377. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  106378. /**
  106379. * Gets the ground mesh created by the helper.
  106380. */
  106381. get: function () {
  106382. return this._ground;
  106383. },
  106384. enumerable: true,
  106385. configurable: true
  106386. });
  106387. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  106388. /**
  106389. * Gets the ground texture created by the helper.
  106390. */
  106391. get: function () {
  106392. return this._groundTexture;
  106393. },
  106394. enumerable: true,
  106395. configurable: true
  106396. });
  106397. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  106398. /**
  106399. * Gets the ground mirror created by the helper.
  106400. */
  106401. get: function () {
  106402. return this._groundMirror;
  106403. },
  106404. enumerable: true,
  106405. configurable: true
  106406. });
  106407. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  106408. /**
  106409. * Gets the ground mirror render list to helps pushing the meshes
  106410. * you wish in the ground reflection.
  106411. */
  106412. get: function () {
  106413. if (this._groundMirror) {
  106414. return this._groundMirror.renderList;
  106415. }
  106416. return null;
  106417. },
  106418. enumerable: true,
  106419. configurable: true
  106420. });
  106421. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  106422. /**
  106423. * Gets the ground material created by the helper.
  106424. */
  106425. get: function () {
  106426. return this._groundMaterial;
  106427. },
  106428. enumerable: true,
  106429. configurable: true
  106430. });
  106431. /**
  106432. * Updates the background according to the new options
  106433. * @param options
  106434. */
  106435. EnvironmentHelper.prototype.updateOptions = function (options) {
  106436. var newOptions = __assign({}, this._options, options);
  106437. if (this._ground && !newOptions.createGround) {
  106438. this._ground.dispose();
  106439. this._ground = null;
  106440. }
  106441. if (this._groundMaterial && !newOptions.createGround) {
  106442. this._groundMaterial.dispose();
  106443. this._groundMaterial = null;
  106444. }
  106445. if (this._groundTexture) {
  106446. if (this._options.groundTexture != newOptions.groundTexture) {
  106447. this._groundTexture.dispose();
  106448. this._groundTexture = null;
  106449. }
  106450. }
  106451. if (this._skybox && !newOptions.createSkybox) {
  106452. this._skybox.dispose();
  106453. this._skybox = null;
  106454. }
  106455. if (this._skyboxMaterial && !newOptions.createSkybox) {
  106456. this._skyboxMaterial.dispose();
  106457. this._skyboxMaterial = null;
  106458. }
  106459. if (this._skyboxTexture) {
  106460. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  106461. this._skyboxTexture.dispose();
  106462. this._skyboxTexture = null;
  106463. }
  106464. }
  106465. if (this._groundMirror && !newOptions.enableGroundMirror) {
  106466. this._groundMirror.dispose();
  106467. this._groundMirror = null;
  106468. }
  106469. if (this._scene.environmentTexture) {
  106470. if (this._options.environmentTexture != newOptions.environmentTexture) {
  106471. this._scene.environmentTexture.dispose();
  106472. }
  106473. }
  106474. this._options = newOptions;
  106475. this._setupBackground();
  106476. this._setupImageProcessing();
  106477. };
  106478. /**
  106479. * Sets the primary color of all the available elements.
  106480. * @param color the main color to affect to the ground and the background
  106481. */
  106482. EnvironmentHelper.prototype.setMainColor = function (color) {
  106483. if (this.groundMaterial) {
  106484. this.groundMaterial.primaryColor = color;
  106485. }
  106486. if (this.skyboxMaterial) {
  106487. this.skyboxMaterial.primaryColor = color;
  106488. }
  106489. if (this.groundMirror) {
  106490. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  106491. }
  106492. };
  106493. /**
  106494. * Setup the image processing according to the specified options.
  106495. */
  106496. EnvironmentHelper.prototype._setupImageProcessing = function () {
  106497. if (this._options.setupImageProcessing) {
  106498. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  106499. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  106500. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  106501. this._setupEnvironmentTexture();
  106502. }
  106503. };
  106504. /**
  106505. * Setup the environment texture according to the specified options.
  106506. */
  106507. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  106508. if (this._scene.environmentTexture) {
  106509. return;
  106510. }
  106511. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  106512. this._scene.environmentTexture = this._options.environmentTexture;
  106513. return;
  106514. }
  106515. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  106516. this._scene.environmentTexture = environmentTexture;
  106517. };
  106518. /**
  106519. * Setup the background according to the specified options.
  106520. */
  106521. EnvironmentHelper.prototype._setupBackground = function () {
  106522. if (!this._rootMesh) {
  106523. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  106524. }
  106525. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  106526. var sceneSize = this._getSceneSize();
  106527. if (this._options.createGround) {
  106528. this._setupGround(sceneSize);
  106529. this._setupGroundMaterial();
  106530. this._setupGroundDiffuseTexture();
  106531. if (this._options.enableGroundMirror) {
  106532. this._setupGroundMirrorTexture(sceneSize);
  106533. }
  106534. this._setupMirrorInGroundMaterial();
  106535. }
  106536. if (this._options.createSkybox) {
  106537. this._setupSkybox(sceneSize);
  106538. this._setupSkyboxMaterial();
  106539. this._setupSkyboxReflectionTexture();
  106540. }
  106541. this._rootMesh.position.x = sceneSize.rootPosition.x;
  106542. this._rootMesh.position.z = sceneSize.rootPosition.z;
  106543. this._rootMesh.position.y = sceneSize.rootPosition.y;
  106544. };
  106545. /**
  106546. * Get the scene sizes according to the setup.
  106547. */
  106548. EnvironmentHelper.prototype._getSceneSize = function () {
  106549. var _this = this;
  106550. var groundSize = this._options.groundSize;
  106551. var skyboxSize = this._options.skyboxSize;
  106552. var rootPosition = this._options.rootPosition;
  106553. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  106554. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  106555. }
  106556. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  106557. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  106558. });
  106559. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  106560. if (this._options.sizeAuto) {
  106561. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  106562. this._scene.activeCamera.upperRadiusLimit) {
  106563. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  106564. skyboxSize = groundSize;
  106565. }
  106566. var sceneDiagonalLenght = sceneDiagonal.length();
  106567. if (sceneDiagonalLenght > groundSize) {
  106568. groundSize = sceneDiagonalLenght * 2;
  106569. skyboxSize = groundSize;
  106570. }
  106571. // 10 % bigger.
  106572. groundSize *= 1.1;
  106573. skyboxSize *= 1.5;
  106574. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  106575. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  106576. }
  106577. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  106578. };
  106579. /**
  106580. * Setup the ground according to the specified options.
  106581. */
  106582. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  106583. var _this = this;
  106584. if (!this._ground || this._ground.isDisposed()) {
  106585. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  106586. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  106587. this._ground.parent = this._rootMesh;
  106588. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  106589. }
  106590. this._ground.receiveShadows = this._options.enableGroundShadow;
  106591. };
  106592. /**
  106593. * Setup the ground material according to the specified options.
  106594. */
  106595. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  106596. if (!this._groundMaterial) {
  106597. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  106598. }
  106599. this._groundMaterial.alpha = this._options.groundOpacity;
  106600. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  106601. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  106602. this._groundMaterial.primaryColor = this._options.groundColor;
  106603. this._groundMaterial.useRGBColor = false;
  106604. this._groundMaterial.enableNoise = true;
  106605. if (this._ground) {
  106606. this._ground.material = this._groundMaterial;
  106607. }
  106608. };
  106609. /**
  106610. * Setup the ground diffuse texture according to the specified options.
  106611. */
  106612. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  106613. if (!this._groundMaterial) {
  106614. return;
  106615. }
  106616. if (this._groundTexture) {
  106617. return;
  106618. }
  106619. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  106620. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  106621. return;
  106622. }
  106623. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  106624. diffuseTexture.gammaSpace = false;
  106625. diffuseTexture.hasAlpha = true;
  106626. this._groundMaterial.diffuseTexture = diffuseTexture;
  106627. };
  106628. /**
  106629. * Setup the ground mirror texture according to the specified options.
  106630. */
  106631. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  106632. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106633. if (!this._groundMirror) {
  106634. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  106635. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  106636. this._groundMirror.anisotropicFilteringLevel = 1;
  106637. this._groundMirror.wrapU = wrapping;
  106638. this._groundMirror.wrapV = wrapping;
  106639. this._groundMirror.gammaSpace = false;
  106640. if (this._groundMirror.renderList) {
  106641. for (var i = 0; i < this._scene.meshes.length; i++) {
  106642. var mesh = this._scene.meshes[i];
  106643. if (mesh !== this._ground &&
  106644. mesh !== this._skybox &&
  106645. mesh !== this._rootMesh) {
  106646. this._groundMirror.renderList.push(mesh);
  106647. }
  106648. }
  106649. }
  106650. }
  106651. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  106652. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  106653. };
  106654. /**
  106655. * Setup the ground to receive the mirror texture.
  106656. */
  106657. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  106658. if (this._groundMaterial) {
  106659. this._groundMaterial.reflectionTexture = this._groundMirror;
  106660. this._groundMaterial.reflectionFresnel = true;
  106661. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  106662. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  106663. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  106664. }
  106665. };
  106666. /**
  106667. * Setup the skybox according to the specified options.
  106668. */
  106669. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  106670. var _this = this;
  106671. if (!this._skybox || this._skybox.isDisposed()) {
  106672. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  106673. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  106674. }
  106675. this._skybox.parent = this._rootMesh;
  106676. };
  106677. /**
  106678. * Setup the skybox material according to the specified options.
  106679. */
  106680. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  106681. if (!this._skybox) {
  106682. return;
  106683. }
  106684. if (!this._skyboxMaterial) {
  106685. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  106686. }
  106687. this._skyboxMaterial.useRGBColor = false;
  106688. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  106689. this._skyboxMaterial.enableNoise = true;
  106690. this._skybox.material = this._skyboxMaterial;
  106691. };
  106692. /**
  106693. * Setup the skybox reflection texture according to the specified options.
  106694. */
  106695. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  106696. if (!this._skyboxMaterial) {
  106697. return;
  106698. }
  106699. if (this._skyboxTexture) {
  106700. return;
  106701. }
  106702. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  106703. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  106704. return;
  106705. }
  106706. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  106707. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  106708. this._skyboxTexture.gammaSpace = false;
  106709. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  106710. };
  106711. /**
  106712. * Dispose all the elements created by the Helper.
  106713. */
  106714. EnvironmentHelper.prototype.dispose = function () {
  106715. if (this._groundMaterial) {
  106716. this._groundMaterial.dispose(true, true);
  106717. }
  106718. if (this._skyboxMaterial) {
  106719. this._skyboxMaterial.dispose(true, true);
  106720. }
  106721. this._rootMesh.dispose(false);
  106722. };
  106723. /**
  106724. * Default ground texture URL.
  106725. */
  106726. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  106727. /**
  106728. * Default skybox texture URL.
  106729. */
  106730. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  106731. /**
  106732. * Default environment texture URL.
  106733. */
  106734. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  106735. return EnvironmentHelper;
  106736. }());
  106737. BABYLON.EnvironmentHelper = EnvironmentHelper;
  106738. })(BABYLON || (BABYLON = {}));
  106739. //# sourceMappingURL=babylon.environmentHelper.js.map
  106740. var BABYLON;
  106741. (function (BABYLON) {
  106742. /** Internal class used to store shapes for emitters */
  106743. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  106744. function ParticleSystemSetEmitterCreationOptions() {
  106745. }
  106746. return ParticleSystemSetEmitterCreationOptions;
  106747. }());
  106748. /**
  106749. * Represents a set of particle systems working together to create a specific effect
  106750. */
  106751. var ParticleSystemSet = /** @class */ (function () {
  106752. function ParticleSystemSet() {
  106753. /**
  106754. * Gets the particle system list
  106755. */
  106756. this.systems = new Array();
  106757. }
  106758. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  106759. /**
  106760. * Gets the emitter node used with this set
  106761. */
  106762. get: function () {
  106763. return this._emitterNode;
  106764. },
  106765. enumerable: true,
  106766. configurable: true
  106767. });
  106768. /**
  106769. * Creates a new emitter mesh as a sphere
  106770. * @param options defines the options used to create the sphere
  106771. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  106772. * @param scene defines the hosting scene
  106773. */
  106774. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  106775. if (this._emitterNode) {
  106776. this._emitterNode.dispose();
  106777. }
  106778. this._emitterCreationOptions = {
  106779. kind: "Sphere",
  106780. options: options,
  106781. renderingGroupId: renderingGroupId
  106782. };
  106783. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  106784. emitterMesh.renderingGroupId = renderingGroupId;
  106785. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  106786. material.emissiveColor = options.color;
  106787. emitterMesh.material = material;
  106788. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  106789. var system = _a[_i];
  106790. system.emitter = emitterMesh;
  106791. }
  106792. this._emitterNode = emitterMesh;
  106793. };
  106794. /**
  106795. * Starts all particle systems of the set
  106796. * @param emitter defines an optional mesh to use as emitter for the particle systems
  106797. */
  106798. ParticleSystemSet.prototype.start = function (emitter) {
  106799. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  106800. var system = _a[_i];
  106801. if (emitter) {
  106802. system.emitter = emitter;
  106803. }
  106804. system.start();
  106805. }
  106806. };
  106807. /**
  106808. * Release all associated resources
  106809. */
  106810. ParticleSystemSet.prototype.dispose = function () {
  106811. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  106812. var system = _a[_i];
  106813. system.dispose();
  106814. }
  106815. this.systems = [];
  106816. if (this._emitterNode) {
  106817. this._emitterNode.dispose();
  106818. this._emitterNode = null;
  106819. }
  106820. };
  106821. /**
  106822. * Serialize the set into a JSON compatible object
  106823. * @returns a JSON compatible representation of the set
  106824. */
  106825. ParticleSystemSet.prototype.serialize = function () {
  106826. var result = {};
  106827. result.systems = [];
  106828. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  106829. var system = _a[_i];
  106830. result.systems.push(system.serialize());
  106831. }
  106832. if (this._emitterNode) {
  106833. result.emitter = this._emitterCreationOptions;
  106834. }
  106835. return result;
  106836. };
  106837. /**
  106838. * Parse a new ParticleSystemSet from a serialized source
  106839. * @param data defines a JSON compatible representation of the set
  106840. * @param scene defines the hosting scene
  106841. * @param gpu defines if we want GPU particles or CPU particles
  106842. * @returns a new ParticleSystemSet
  106843. */
  106844. ParticleSystemSet.Parse = function (data, scene, gpu) {
  106845. if (gpu === void 0) { gpu = false; }
  106846. var result = new ParticleSystemSet();
  106847. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  106848. scene = scene || BABYLON.Engine.LastCreatedScene;
  106849. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  106850. var system = _a[_i];
  106851. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  106852. }
  106853. if (data.emitter) {
  106854. var options = data.emitter.options;
  106855. switch (data.emitter.kind) {
  106856. case "Sphere":
  106857. result.setEmitterAsSphere({
  106858. diameter: options.diameter,
  106859. segments: options.segments,
  106860. color: BABYLON.Color3.FromArray(options.color)
  106861. }, data.emitter.renderingGroupId, scene);
  106862. break;
  106863. }
  106864. }
  106865. return result;
  106866. };
  106867. return ParticleSystemSet;
  106868. }());
  106869. BABYLON.ParticleSystemSet = ParticleSystemSet;
  106870. })(BABYLON || (BABYLON = {}));
  106871. //# sourceMappingURL=babylon.particleSystemSet.js.map
  106872. var BABYLON;
  106873. (function (BABYLON) {
  106874. /**
  106875. * This class is made for on one-liner static method to help creating particle system set.
  106876. */
  106877. var ParticleHelper = /** @class */ (function () {
  106878. function ParticleHelper() {
  106879. }
  106880. /**
  106881. * Create a default particle system that you can tweak
  106882. * @param emitter defines the emitter to use
  106883. * @param capacity defines the system capacity (default is 500 particles)
  106884. * @param scene defines the hosting scene
  106885. * @returns the new Particle system
  106886. */
  106887. ParticleHelper.CreateDefault = function (emitter, capacity, scene) {
  106888. if (capacity === void 0) { capacity = 500; }
  106889. var system = new BABYLON.ParticleSystem("default system", capacity, scene);
  106890. system.emitter = emitter;
  106891. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  106892. system.createConeEmitter(0.1, Math.PI / 4);
  106893. // Particle color
  106894. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  106895. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  106896. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  106897. // Particle Size
  106898. system.minSize = 0.1;
  106899. system.maxSize = 0.1;
  106900. // Emission speed
  106901. system.minEmitPower = 2;
  106902. system.maxEmitPower = 2;
  106903. // Update speed
  106904. system.updateSpeed = 1 / 60;
  106905. system.emitRate = 30;
  106906. return system;
  106907. };
  106908. /**
  106909. * This is the main static method (one-liner) of this helper to create different particle systems
  106910. * @param type This string represents the type to the particle system to create
  106911. * @param scene The scene where the particle system should live
  106912. * @param gpu If the system will use gpu
  106913. * @returns the ParticleSystemSet created
  106914. */
  106915. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  106916. if (gpu === void 0) { gpu = false; }
  106917. if (!scene) {
  106918. scene = BABYLON.Engine.LastCreatedScene;
  106919. ;
  106920. }
  106921. var token = {};
  106922. scene._addPendingData(token);
  106923. return new Promise(function (resolve, reject) {
  106924. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  106925. scene._removePendingData(token);
  106926. return reject("Particle system with GPU is not supported.");
  106927. }
  106928. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  106929. scene._removePendingData(token);
  106930. var newData = JSON.parse(data.toString());
  106931. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  106932. }, undefined, undefined, undefined, function (req, exception) {
  106933. scene._removePendingData(token);
  106934. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  106935. });
  106936. });
  106937. };
  106938. /**
  106939. * Static function used to export a particle system to a ParticleSystemSet variable.
  106940. * Please note that the emitter shape is not exported
  106941. * @param system defines the particle systems to export
  106942. */
  106943. ParticleHelper.ExportSet = function (systems) {
  106944. var set = new BABYLON.ParticleSystemSet();
  106945. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  106946. var system = systems_1[_i];
  106947. set.systems.push(system);
  106948. }
  106949. return set;
  106950. };
  106951. /**
  106952. * Gets or sets base Assets URL
  106953. */
  106954. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  106955. return ParticleHelper;
  106956. }());
  106957. BABYLON.ParticleHelper = ParticleHelper;
  106958. })(BABYLON || (BABYLON = {}));
  106959. //# sourceMappingURL=babylon.particleHelper.js.map
  106960. var BABYLON;
  106961. (function (BABYLON) {
  106962. /**
  106963. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  106964. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  106965. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  106966. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  106967. */
  106968. var VideoDome = /** @class */ (function (_super) {
  106969. __extends(VideoDome, _super);
  106970. /**
  106971. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  106972. * @param name Element's name, child elements will append suffixes for their own names.
  106973. * @param urlsOrVideo defines the url(s) or the video element to use
  106974. * @param options An object containing optional or exposed sub element properties
  106975. */
  106976. function VideoDome(name, urlsOrVideo, options, scene) {
  106977. var _this = _super.call(this, name, scene) || this;
  106978. _this._useDirectMapping = false;
  106979. // set defaults and manage values
  106980. name = name || "videoDome";
  106981. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  106982. options.clickToPlay = Boolean(options.clickToPlay);
  106983. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  106984. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  106985. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  106986. if (options.useDirectMapping === undefined) {
  106987. _this._useDirectMapping = true;
  106988. }
  106989. else {
  106990. _this._useDirectMapping = options.useDirectMapping;
  106991. }
  106992. _this._setReady(false);
  106993. // create
  106994. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  106995. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  106996. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  106997. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  106998. texture.onLoadObservable.addOnce(function () {
  106999. _this._setReady(true);
  107000. });
  107001. // configure material
  107002. material.useEquirectangularFOV = true;
  107003. material.fovMultiplier = 1.0;
  107004. material.opacityFresnel = false;
  107005. if (_this._useDirectMapping) {
  107006. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107007. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107008. material.diffuseTexture = texture;
  107009. }
  107010. else {
  107011. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  107012. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107013. material.reflectionTexture = texture;
  107014. }
  107015. // configure mesh
  107016. _this._mesh.material = material;
  107017. _this._mesh.parent = _this;
  107018. // optional configuration
  107019. if (options.clickToPlay) {
  107020. scene.onPointerUp = function () {
  107021. _this._videoTexture.video.play();
  107022. };
  107023. }
  107024. return _this;
  107025. }
  107026. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  107027. /**
  107028. * Gets the video texture being displayed on the sphere
  107029. */
  107030. get: function () {
  107031. return this._videoTexture;
  107032. },
  107033. enumerable: true,
  107034. configurable: true
  107035. });
  107036. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  107037. /**
  107038. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  107039. * Also see the options.resolution property.
  107040. */
  107041. get: function () {
  107042. return this._material.fovMultiplier;
  107043. },
  107044. set: function (value) {
  107045. this._material.fovMultiplier = value;
  107046. },
  107047. enumerable: true,
  107048. configurable: true
  107049. });
  107050. /**
  107051. * Releases resources associated with this node.
  107052. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  107053. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  107054. */
  107055. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  107056. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  107057. this._videoTexture.dispose();
  107058. this._mesh.dispose();
  107059. this._material.dispose();
  107060. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  107061. };
  107062. return VideoDome;
  107063. }(BABYLON.TransformNode));
  107064. BABYLON.VideoDome = VideoDome;
  107065. })(BABYLON || (BABYLON = {}));
  107066. //# sourceMappingURL=babylon.videoDome.js.map
  107067. var BABYLON;
  107068. (function (BABYLON) {
  107069. /**
  107070. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  107071. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  107072. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  107073. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  107074. */
  107075. var PhotoDome = /** @class */ (function (_super) {
  107076. __extends(PhotoDome, _super);
  107077. /**
  107078. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  107079. * @param name Element's name, child elements will append suffixes for their own names.
  107080. * @param urlsOfPhoto defines the url of the photo to display
  107081. * @param options defines an object containing optional or exposed sub element properties
  107082. * @param onError defines a callback called when an error occured while loading the texture
  107083. */
  107084. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  107085. if (onError === void 0) { onError = null; }
  107086. var _this = _super.call(this, name, scene) || this;
  107087. _this._useDirectMapping = false;
  107088. /**
  107089. * Observable raised when an error occured while loading the 360 image
  107090. */
  107091. _this.onLoadErrorObservable = new BABYLON.Observable();
  107092. // set defaults and manage values
  107093. name = name || "photoDome";
  107094. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  107095. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  107096. if (options.useDirectMapping === undefined) {
  107097. _this._useDirectMapping = true;
  107098. }
  107099. else {
  107100. _this._useDirectMapping = options.useDirectMapping;
  107101. }
  107102. _this._setReady(false);
  107103. // create
  107104. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  107105. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  107106. // configure material
  107107. material.opacityFresnel = false;
  107108. material.useEquirectangularFOV = true;
  107109. material.fovMultiplier = 1.0;
  107110. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  107111. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  107112. if (onError) {
  107113. onError(message, exception);
  107114. }
  107115. });
  107116. _this.photoTexture.onLoadObservable.addOnce(function () {
  107117. _this._setReady(true);
  107118. });
  107119. // configure mesh
  107120. _this._mesh.material = material;
  107121. _this._mesh.parent = _this;
  107122. return _this;
  107123. }
  107124. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  107125. /**
  107126. * Gets or sets the texture being displayed on the sphere
  107127. */
  107128. get: function () {
  107129. return this._photoTexture;
  107130. },
  107131. set: function (value) {
  107132. if (this._photoTexture === value) {
  107133. return;
  107134. }
  107135. this._photoTexture = value;
  107136. if (this._useDirectMapping) {
  107137. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107138. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107139. this._material.diffuseTexture = this._photoTexture;
  107140. }
  107141. else {
  107142. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  107143. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107144. this._material.reflectionTexture = this._photoTexture;
  107145. }
  107146. },
  107147. enumerable: true,
  107148. configurable: true
  107149. });
  107150. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  107151. /**
  107152. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  107153. * Also see the options.resolution property.
  107154. */
  107155. get: function () {
  107156. return this._material.fovMultiplier;
  107157. },
  107158. set: function (value) {
  107159. this._material.fovMultiplier = value;
  107160. },
  107161. enumerable: true,
  107162. configurable: true
  107163. });
  107164. /**
  107165. * Releases resources associated with this node.
  107166. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  107167. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  107168. */
  107169. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  107170. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  107171. this._photoTexture.dispose();
  107172. this._mesh.dispose();
  107173. this._material.dispose();
  107174. this.onLoadErrorObservable.clear();
  107175. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  107176. };
  107177. return PhotoDome;
  107178. }(BABYLON.TransformNode));
  107179. BABYLON.PhotoDome = PhotoDome;
  107180. })(BABYLON || (BABYLON = {}));
  107181. //# sourceMappingURL=babylon.photoDome.js.map
  107182. var BABYLON;
  107183. (function (BABYLON) {
  107184. BABYLON.Engine.prototype.createQuery = function () {
  107185. return this._gl.createQuery();
  107186. };
  107187. BABYLON.Engine.prototype.deleteQuery = function (query) {
  107188. this._gl.deleteQuery(query);
  107189. return this;
  107190. };
  107191. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  107192. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  107193. };
  107194. BABYLON.Engine.prototype.getQueryResult = function (query) {
  107195. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  107196. };
  107197. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  107198. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  107199. this._gl.beginQuery(glAlgorithm, query);
  107200. return this;
  107201. };
  107202. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  107203. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  107204. this._gl.endQuery(glAlgorithm);
  107205. return this;
  107206. };
  107207. BABYLON.Engine.prototype._createTimeQuery = function () {
  107208. var timerQuery = this.getCaps().timerQuery;
  107209. if (timerQuery.createQueryEXT) {
  107210. return timerQuery.createQueryEXT();
  107211. }
  107212. return this.createQuery();
  107213. };
  107214. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  107215. var timerQuery = this.getCaps().timerQuery;
  107216. if (timerQuery.deleteQueryEXT) {
  107217. timerQuery.deleteQueryEXT(query);
  107218. return;
  107219. }
  107220. this.deleteQuery(query);
  107221. };
  107222. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  107223. var timerQuery = this.getCaps().timerQuery;
  107224. if (timerQuery.getQueryObjectEXT) {
  107225. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  107226. }
  107227. return this.getQueryResult(query);
  107228. };
  107229. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  107230. var timerQuery = this.getCaps().timerQuery;
  107231. if (timerQuery.getQueryObjectEXT) {
  107232. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  107233. }
  107234. return this.isQueryResultAvailable(query);
  107235. };
  107236. BABYLON.Engine.prototype.startTimeQuery = function () {
  107237. var caps = this.getCaps();
  107238. var timerQuery = caps.timerQuery;
  107239. if (!timerQuery) {
  107240. return null;
  107241. }
  107242. var token = new BABYLON._TimeToken();
  107243. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  107244. if (caps.canUseTimestampForTimerQuery) {
  107245. token._startTimeQuery = this._createTimeQuery();
  107246. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  107247. }
  107248. else {
  107249. if (this._currentNonTimestampToken) {
  107250. return this._currentNonTimestampToken;
  107251. }
  107252. token._timeElapsedQuery = this._createTimeQuery();
  107253. if (timerQuery.beginQueryEXT) {
  107254. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  107255. }
  107256. else {
  107257. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  107258. }
  107259. this._currentNonTimestampToken = token;
  107260. }
  107261. return token;
  107262. };
  107263. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  107264. var caps = this.getCaps();
  107265. var timerQuery = caps.timerQuery;
  107266. if (!timerQuery || !token) {
  107267. return -1;
  107268. }
  107269. if (caps.canUseTimestampForTimerQuery) {
  107270. if (!token._startTimeQuery) {
  107271. return -1;
  107272. }
  107273. if (!token._endTimeQuery) {
  107274. token._endTimeQuery = this._createTimeQuery();
  107275. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  107276. }
  107277. }
  107278. else if (!token._timeElapsedQueryEnded) {
  107279. if (!token._timeElapsedQuery) {
  107280. return -1;
  107281. }
  107282. if (timerQuery.endQueryEXT) {
  107283. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  107284. }
  107285. else {
  107286. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  107287. }
  107288. token._timeElapsedQueryEnded = true;
  107289. }
  107290. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  107291. var available = false;
  107292. if (token._endTimeQuery) {
  107293. available = this._getTimeQueryAvailability(token._endTimeQuery);
  107294. }
  107295. else if (token._timeElapsedQuery) {
  107296. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  107297. }
  107298. if (available && !disjoint) {
  107299. var result = 0;
  107300. if (caps.canUseTimestampForTimerQuery) {
  107301. if (!token._startTimeQuery || !token._endTimeQuery) {
  107302. return -1;
  107303. }
  107304. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  107305. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  107306. result = timeEnd - timeStart;
  107307. this._deleteTimeQuery(token._startTimeQuery);
  107308. this._deleteTimeQuery(token._endTimeQuery);
  107309. token._startTimeQuery = null;
  107310. token._endTimeQuery = null;
  107311. }
  107312. else {
  107313. if (!token._timeElapsedQuery) {
  107314. return -1;
  107315. }
  107316. result = this._getTimeQueryResult(token._timeElapsedQuery);
  107317. this._deleteTimeQuery(token._timeElapsedQuery);
  107318. token._timeElapsedQuery = null;
  107319. token._timeElapsedQueryEnded = false;
  107320. this._currentNonTimestampToken = null;
  107321. }
  107322. return result;
  107323. }
  107324. return -1;
  107325. };
  107326. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  107327. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  107328. };
  107329. // We also need to update AbstractMesh as there is a portion of the code there
  107330. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  107331. var engine = this.getEngine();
  107332. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  107333. this._isOccluded = false;
  107334. return;
  107335. }
  107336. if (engine.webGLVersion < 2 || this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  107337. this._isOccluded = false;
  107338. return;
  107339. }
  107340. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  107341. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  107342. if (isOcclusionQueryAvailable) {
  107343. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  107344. this._isOcclusionQueryInProgress = false;
  107345. this._occlusionInternalRetryCounter = 0;
  107346. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  107347. }
  107348. else {
  107349. this._occlusionInternalRetryCounter++;
  107350. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  107351. this._isOcclusionQueryInProgress = false;
  107352. this._occlusionInternalRetryCounter = 0;
  107353. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  107354. // if strict continue the last state of the object.
  107355. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  107356. }
  107357. else {
  107358. return;
  107359. }
  107360. }
  107361. }
  107362. var scene = this.getScene();
  107363. if (scene.getBoundingBoxRenderer) {
  107364. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  107365. if (!this._occlusionQuery) {
  107366. this._occlusionQuery = engine.createQuery();
  107367. }
  107368. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  107369. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  107370. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  107371. this._isOcclusionQueryInProgress = true;
  107372. }
  107373. };
  107374. })(BABYLON || (BABYLON = {}));
  107375. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  107376. var BABYLON;
  107377. (function (BABYLON) {
  107378. /**
  107379. * Class used to generate noise procedural textures
  107380. */
  107381. var NoiseProceduralTexture = /** @class */ (function (_super) {
  107382. __extends(NoiseProceduralTexture, _super);
  107383. /**
  107384. * Creates a new NoiseProceduralTexture
  107385. * @param name defines the name fo the texture
  107386. * @param size defines the size of the texture (default is 256)
  107387. * @param scene defines the hosting scene
  107388. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  107389. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  107390. */
  107391. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  107392. if (size === void 0) { size = 256; }
  107393. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  107394. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  107395. _this._time = 0;
  107396. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  107397. _this.brightness = 0.2;
  107398. /** Defines the number of octaves to process */
  107399. _this.octaves = 3;
  107400. /** Defines the level of persistence (0.8 by default) */
  107401. _this.persistence = 0.8;
  107402. /** Gets or sets animation speed factor (default is 1) */
  107403. _this.animationSpeedFactor = 1;
  107404. _this._updateShaderUniforms();
  107405. return _this;
  107406. }
  107407. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  107408. var scene = this.getScene();
  107409. if (!scene) {
  107410. return;
  107411. }
  107412. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  107413. this.setFloat("brightness", this.brightness);
  107414. this.setFloat("persistence", this.persistence);
  107415. this.setFloat("timeScale", this._time);
  107416. };
  107417. NoiseProceduralTexture.prototype._getDefines = function () {
  107418. return "#define OCTAVES " + this.octaves;
  107419. };
  107420. /** Generate the current state of the procedural texture */
  107421. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  107422. this._updateShaderUniforms();
  107423. _super.prototype.render.call(this, useCameraPostProcess);
  107424. };
  107425. /**
  107426. * Serializes this noise procedural texture
  107427. * @returns a serialized noise procedural texture object
  107428. */
  107429. NoiseProceduralTexture.prototype.serialize = function () {
  107430. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  107431. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  107432. return serializationObject;
  107433. };
  107434. /**
  107435. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  107436. * @param parsedTexture defines parsed texture data
  107437. * @param scene defines the current scene
  107438. * @param rootUrl defines the root URL containing noise procedural texture information
  107439. * @returns a parsed NoiseProceduralTexture
  107440. */
  107441. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  107442. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  107443. return texture;
  107444. };
  107445. return NoiseProceduralTexture;
  107446. }(BABYLON.ProceduralTexture));
  107447. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  107448. })(BABYLON || (BABYLON = {}));
  107449. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  107450. var __assign = (this && this.__assign) || function () {
  107451. __assign = Object.assign || function(t) {
  107452. for (var s, i = 1, n = arguments.length; i < n; i++) {
  107453. s = arguments[i];
  107454. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  107455. t[p] = s[p];
  107456. }
  107457. return t;
  107458. };
  107459. return __assign.apply(this, arguments);
  107460. };
  107461. var BABYLON;
  107462. (function (BABYLON) {
  107463. /**
  107464. * This can helps recording videos from BabylonJS.
  107465. * This is based on the available WebRTC functionalities of the browser.
  107466. *
  107467. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  107468. */
  107469. var VideoRecorder = /** @class */ (function () {
  107470. /**
  107471. * Create a new VideoCapture object which can help converting what you see in Babylon to
  107472. * a video file.
  107473. * @param engine Defines the BabylonJS Engine you wish to record
  107474. * @param options Defines options that can be used to customized the capture
  107475. */
  107476. function VideoRecorder(engine, options) {
  107477. if (options === void 0) { options = null; }
  107478. if (!VideoRecorder.IsSupported(engine)) {
  107479. throw "Your browser does not support recording so far.";
  107480. }
  107481. var canvas = engine.getRenderingCanvas();
  107482. if (!canvas) {
  107483. throw "The babylon engine must have a canvas to be recorded";
  107484. }
  107485. this._canvas = canvas;
  107486. this._canvas.isRecording = false;
  107487. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  107488. var stream = this._canvas.captureStream(this._options.fps);
  107489. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  107490. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  107491. this._mediaRecorder.onerror = this._handleError.bind(this);
  107492. this._mediaRecorder.onstop = this._handleStop.bind(this);
  107493. }
  107494. /**
  107495. * Returns wehther or not the VideoRecorder is available in your browser.
  107496. * @param engine Defines the Babylon Engine to check the support for
  107497. * @returns true if supported otherwise false
  107498. */
  107499. VideoRecorder.IsSupported = function (engine) {
  107500. var canvas = engine.getRenderingCanvas();
  107501. return (!!canvas && typeof canvas.captureStream === "function");
  107502. };
  107503. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  107504. /**
  107505. * True wether a recording is already in progress.
  107506. */
  107507. get: function () {
  107508. return !!this._canvas && this._canvas.isRecording;
  107509. },
  107510. enumerable: true,
  107511. configurable: true
  107512. });
  107513. /**
  107514. * Stops the current recording before the default capture timeout passed in the startRecording
  107515. * functions.
  107516. */
  107517. VideoRecorder.prototype.stopRecording = function () {
  107518. if (!this._canvas || !this._mediaRecorder) {
  107519. return;
  107520. }
  107521. if (!this.isRecording) {
  107522. return;
  107523. }
  107524. this._canvas.isRecording = false;
  107525. this._mediaRecorder.stop();
  107526. };
  107527. /**
  107528. * Starts recording the canvas for a max duration specified in parameters.
  107529. * @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.
  107530. * @param maxDuration Defines the maximum recording time in seconds.
  107531. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  107532. * @return a promise callback at the end of the recording with the video data in Blob.
  107533. */
  107534. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  107535. var _this = this;
  107536. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  107537. if (maxDuration === void 0) { maxDuration = 7; }
  107538. if (!this._canvas || !this._mediaRecorder) {
  107539. throw "Recorder has already been disposed";
  107540. }
  107541. if (this.isRecording) {
  107542. throw "Recording already in progress";
  107543. }
  107544. if (maxDuration > 0) {
  107545. setTimeout(function () {
  107546. _this.stopRecording();
  107547. }, maxDuration * 1000);
  107548. }
  107549. this._fileName = fileName;
  107550. this._recordedChunks = [];
  107551. this._resolve = null;
  107552. this._reject = null;
  107553. this._canvas.isRecording = true;
  107554. this._mediaRecorder.start(this._options.recordChunckSize);
  107555. return new Promise(function (resolve, reject) {
  107556. _this._resolve = resolve;
  107557. _this._reject = reject;
  107558. });
  107559. };
  107560. /**
  107561. * Releases internal resources used during the recording.
  107562. */
  107563. VideoRecorder.prototype.dispose = function () {
  107564. this._canvas = null;
  107565. this._mediaRecorder = null;
  107566. this._recordedChunks = [];
  107567. this._fileName = null;
  107568. this._resolve = null;
  107569. this._reject = null;
  107570. };
  107571. VideoRecorder.prototype._handleDataAvailable = function (event) {
  107572. if (event.data.size > 0) {
  107573. this._recordedChunks.push(event.data);
  107574. }
  107575. };
  107576. VideoRecorder.prototype._handleError = function (event) {
  107577. this.stopRecording();
  107578. if (this._reject) {
  107579. this._reject(event.error);
  107580. }
  107581. else {
  107582. throw new event.error;
  107583. }
  107584. };
  107585. VideoRecorder.prototype._handleStop = function () {
  107586. this.stopRecording();
  107587. var superBuffer = new Blob(this._recordedChunks);
  107588. if (this._resolve) {
  107589. this._resolve(superBuffer);
  107590. }
  107591. window.URL.createObjectURL(superBuffer);
  107592. if (this._fileName) {
  107593. BABYLON.Tools.Download(superBuffer, this._fileName);
  107594. }
  107595. };
  107596. VideoRecorder._defaultOptions = {
  107597. mimeType: "video/webm",
  107598. fps: 25,
  107599. recordChunckSize: 3000
  107600. };
  107601. return VideoRecorder;
  107602. }());
  107603. BABYLON.VideoRecorder = VideoRecorder;
  107604. })(BABYLON || (BABYLON = {}));
  107605. //# sourceMappingURL=babylon.videoRecorder.js.map
  107606. 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\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#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\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>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 baseColor=texture2D(diffuseSampler,vUV);\nbaseColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\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> \noutFragColor=texture(textureSampler,vUV)*vColor;\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;\nuniform float directionRandomizer;\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#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#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 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\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\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#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,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\noutDirection=direction+gravity*timeDelta;\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 dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(outAge*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"};
  107607. 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};"};
  107608. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  107609. globalObject["BABYLON"] = BABYLON;
  107610. //backwards compatibility
  107611. if(typeof earcut !== 'undefined') {
  107612. globalObject["Earcut"] = {
  107613. earcut: earcut
  107614. };
  107615. }
  107616. return BABYLON;
  107617. });